[英]Typescript conditional type missing properties
我无法理解为什么以下 TypeScript 代码会失败,而看似一切都应该没问题:
interface Base { basic: boolean };
interface Super { basic: boolean; extra: boolean };
type Options<T> = T extends Super ? { isSuper: boolean } : { notSuper: boolean }
const baseOptions: Options<{ basic: boolean }> = { notSuper: true }; // ok
const superOptions: Options<{ basic: boolean; extra: boolean }> = { isSuper: true }; // ok
type MakeOptions = <T>() => Options<T>
function withOptions <T>(makeOptions: MakeOptions): void {
const options = makeOptions<T>();
console.log(options.notSuper); // Error: Property 'notSuper' does not exist on type 'Options<T>'.(2339)
console.log(options.isSuper); // Error: Property 'isSuper' does not exist on type 'Options<T>'.(2339)
}
我希望options.isSuper
undefined | { isSuper: boolean }
undefined | { isSuper: boolean }
和options.notSuper
undefined | { notSuper: boolean }
undefined | { notSuper: boolean }
相反,Typescript 将这些属性全部删除。
更改为时问题已解决
type Options<T> = T extends Super ? { isSuper: boolean; notSuper?: undefined } : { notSuper: boolean; isSuper?: undefined }
但这似乎没有必要。
在Options<T>
中,您希望它返回带有参数isSuper
或notSuper
我在他们两个的接口中添加。
interface IisSuper { isSuper: boolean }
interface InotSuper { notSuper: boolean }
在Options<T>
中,因为它可以是上述接口之一,所以我为它创建了一个名为TSuper
的联合类型。
type Options<T> = T extends Super ? IisSuper : InotSuper
type TSuper = IisSuper | InotSuper
在 function withOptions<T>
中,我使用了as
关键字,这是一个类型断言,它告诉编译器将 object 视为另一种类型,而不是编译器推断 ZA8CFDE6331BD59EB2666F8911ZB4 的类型。 在这种情况下, Options<T>
可以作为IisSuper
和InotSuper
的并集存在。
由于 Typescript 无法保证运行时options
的类型,因为您想访问notSuper
或isSuper
因此您必须使用in
关键字缩小 scope 的options
,以访问所需类型的参数。
function withOptions <T>(makeOptions: MakeOptions): void {
const options = makeOptions<T>() as TSuper;
if('notSuper' in options){
console.log(options.notSuper);
}
else if('isSuper' in options){
console.log(options.isSuper);
}
}
最终代码:
interface Base { basic: boolean };
interface Super { basic: boolean; extra: boolean };
interface IisSuper { isSuper: boolean }
interface InotSuper { notSuper: boolean }
type Options<T> = T extends Super ? IisSuper : InotSuper
type MakeOptions = <T>() => Options<T>
type TSuper = IisSuper | InotSuper
const baseOptions: Options<{ basic: boolean }> = { notSuper: true };
const superOptions: Options<{ basic: boolean; extra: boolean }> = { isSuper: true };
function withOptions <T>(makeOptions: MakeOptions): void {
const options = makeOptions<T>() as TSuper;
if('notSuper' in options){
console.log(options.notSuper);
}
else if('isSuper' in options){
console.log(options.isSuper);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.