如何让TypeScript条件式对象属性的类型不为undefined?
问题描述
我有一个带有条件属性的对象,代码如下:
function someCondition() { return Math.random() > .5 ? true : false } const DICTIONARY = { propertyA: 'propertyA' as const, ...(someCondition() && { propertyB: 'propertyB' as const, }), };
我预期该对象的类型应为:
{ propertyB?: "propertyB"; propertyA: "propertyA"; }
但TypeScript实际推断出的类型却是:
{ propertyB?: "propertyB" | undefined; propertyA: "propertyA"; }
我需要让propertyB仅为可选属性——即存在时值只能是"propertyB",不存在则无该属性,不能为undefined。手动定义类型始终没得到正确结果,请问该如何处理?
解决方案
方法1:手动定义目标类型并断言
先明确目标类型,通过类型断言告知TypeScript对象符合该类型:
type TargetDict = { propertyA: "propertyA"; propertyB?: "propertyB"; }; function someCondition() { return Math.random() > .5; } const DICTIONARY = { propertyA: 'propertyA' as const, ...(someCondition() && { propertyB: 'propertyB' as const, }), } as TargetDict;
方法2:使用Object.assign替代扩展运算符
TypeScript对Object.assign的类型推断更贴合预期的可选属性逻辑,避免扩展运算符带来的undefined类型污染:
function someCondition() { return Math.random() > .5; } const DICTIONARY = Object.assign( { propertyA: 'propertyA' as const }, someCondition() ? { propertyB: 'propertyB' as const } : {} );
此时TypeScript会自动推断出正确类型:{ propertyA: "propertyA"; propertyB?: "propertyB"; }。
方法3:自定义工具类型清理推断结果
如果不想手动定义完整类型,可以自定义工具类型移除可选属性的undefined可能性:
type OptionalWithoutUndefined<T> = { [K in keyof T]?: Exclude<T[K], undefined>; }; function someCondition() { return Math.random() > .5; } const DICTIONARY = { propertyA: 'propertyA' as const, ...(someCondition() && { propertyB: 'propertyB' as const, }), } as OptionalWithoutUndefined<typeof DICTIONARY>;
内容的提问来源于stack exchange,提问作者Dimitris Karagiannis
相关产品推荐
相关产品推荐

