TypeScript中如何动态检测未赋值的可选属性类型?
TypeScript中如何检查可选属性是否未被赋值(类型层面)
问题描述
我想在TypeScript中对可选属性做类型检查,判断它未被赋值时是否为undefined,以此区分“故意省略该属性”的场景。但下面的代码结果不符合预期:
type A = { aa?: string } const a:A = {} const { aa } = a type B = typeof aa extends undefined ? true : false // 实际结果:false,预期:true
明明没有给aa赋值,为什么typeof aa的类型不是undefined,导致B为false?该怎么实现动态检查未赋值时的类型?
原因分析
这是因为你把{}赋值给了类型为A的变量a,在TypeScript的静态类型系统中,a的类型依然是A——而A的aa属性类型是string | undefined(可选属性的本质是允许属性不存在,类型自动包含undefined)。所以typeof aa的类型是string | undefined,当用它和undefined做extends判断时,因为联合类型里包含string,条件判断结果为false。
解决方案
1. 运行时类型守卫+类型缩小
通过运行时的判断让TypeScript自动缩小类型,此时就能准确识别aa是否为undefined:
type A = { aa?: string } const a:A = {} const { aa } = a // 运行时判断后,类型系统会识别aa的类型为undefined if (aa === undefined) { type B = typeof aa extends undefined ? true : false // true }
2. 让变量类型更精确(const断言)
如果要在类型层面直接确认属性未被赋值,可以用const断言让TypeScript推断出更精确的变量类型,而不是依赖手动指定的A类型:
// 用const断言让a的类型为{},而非A const a = {} as const const { aa } = a type B = typeof aa extends undefined ? true : false // true
3. 自定义工具类型检查属性是否为undefined
可以编写工具类型,针对特定对象类型检查目标属性是否仅为undefined:
type IsPropertyUndefined<T, K extends keyof any> = K extends keyof T ? T[K] extends undefined ? true : false : true; type A = { aa?: string } type EmptyA = {} // 检查EmptyA类型的aa属性:true type B = IsPropertyUndefined<EmptyA, 'aa'> // 检查A类型的aa属性:false(因为A的aa是string | undefined) type C = IsPropertyUndefined<A, 'aa'>
内容的提问来源于stack exchange,提问作者CliQ
相关产品推荐
相关产品推荐

