【发布时间】:2022-01-19 19:47:56
【问题描述】:
我正在尝试编写一个使用泛型和条件类型返回值的函数,如下所示:
interface Foo<T> {
bar: T extends true ? string : undefined;
id: string;
}
interface Options<T> {
withBar?: T;
}
function createFoo<T extends boolean>({ withBar }: Options<T>): Foo<T> {
return {
id: 'foo',
...(withBar && { bar: 'baz' }),
};
}
上面会抛出以下类型错误:
Type '{ bar?: "baz" | undefined; id: string; }' is not assignable to type 'Foo<T>'.
Types of property 'bar' are incompatible.
Type '"baz" | undefined' is not assignable to type 'T extends true ? string : undefined'.
Type 'undefined' is not assignable to type 'T extends true ? string : undefined'.
有人可以帮我理解为什么会这样吗?我指定类型可以是未定义的,所以应该允许它是未定义的。
此外,我想在给定某些参数的情况下获取函数的返回类型,而无需实际调用它。这可能吗?
例如ReturnType<typeof createFoo> 不会为我提供正确的用法类型 createFoo({ withBar: true }) 因为它还不知道用法。
【问题讨论】:
-
“我指定类型可以是未定义的,所以应该允许它是未定义的。” 好吧...您具体说明在一个特定情况下它是未定义,并且 Typescript 无法确定您的代码确保特定情况由您的函数逻辑处理。 Typescript 很难验证函数的逻辑是否满足条件返回类型的约定。这对于编译器来说很难跟踪,因为它并没有真正执行你的代码。
标签: typescript