You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中实现运行时判断类型是否可为undefined?

需求:实现判断类型是否可赋值为undefined的运行时函数

我希望编写一个函数,用于判断传入的泛型类型是否能够被赋值为undefined,示例代码如下:

type Person = { name: string, address: string | undefined }
type A = Person['address']

const isUndefinedTyped = <T>(): boolean => { throw Error('not implemented') }

isUndefinedTyped<Person>() // 期望返回 false
isUndefinedTyped<A>()      // 期望返回 true

简单来说,我想让TypeScript将编译时的类型信息内联到运行时逻辑中。我在TypeScript设计目标文档中看到以下描述:

Provide additional runtime functionality or libraries. Instead, use TypeScript to describe existing libraries

这说明提供额外的运行时功能并非TypeScript的设计目标。我不确定自己的理解是否正确,也不清楚这个需求到底是否能够实现。


Scala 3中的参考实现

作为对比,在Scala 3中可以通过以下代码实现类似功能:

import scala.compiletime.summonFrom

trait IsNull[A] { }

object IsNull:
  given [A]: IsNull[Option[A]] = new IsNull[Option[A]] { }
  given IsNull[Null] = new IsNull[Null] { }

  inline def check[A]: Boolean =
    summonFrom {
      case given IsNull[A] => true
      case _ => false
    }

println(IsNull.check[Option[String]])  // 输出 true
println(IsNull.check[Option[Int]])     // 输出 true
println(IsNull.check[Int])             // 输出 false

内容的提问来源于stack exchange,提问作者chuwy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 03:32:29