如何在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
相关产品推荐
相关产品推荐

