gpt4 book ai didi

typescript 条件类型缺少属性

转载 作者:行者123 更新时间:2023-12-04 03:42:03 24 4
gpt4 key购买 nike

我无法理解为什么下面的 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 }options.notSuper成为 undefined | { notSuper: boolean }相反,Typescript 将这些属性全部删除。
更改为时问题已解决
type Options<T> = T extends Super ? { isSuper: boolean; notSuper?: undefined } : { notSuper: boolean; isSuper?: undefined }
但这似乎没有必要。
Playground

最佳答案

Options<T>因为你希望它返回一个带有参数 isSuper 的对象或 notSuper我为他们两个都添加了一个界面。

interface IisSuper { isSuper: boolean }
interface InotSuper { notSuper: boolean }
Options<T>因为它可以是上述接口(interface)之一,所以我为其创建了一个联合类型,称为 TSuper .
type Options<T> = T extends Super ? IisSuper : InotSuper
type TSuper = IisSuper | InotSuper
在函数 withOptions<T>我用了 as关键字,它是一个类型断言,它告诉编译器将对象视为另一种类型,而不是编译器推断对象的类型。在这种情况下,它是两个 IisSuper 的并集。和 InotSuper其中 Options<T>可以作为。
由于 Typescript 无法保证 options 的类型在运行时,您想访问 notSuperisSuper所以你必须使用 in 来缩小范围 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);
}
}

关于 typescript 条件类型缺少属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65855858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com