gpt4 book ai didi

typescript - 条件泛型的返回类型不正确

转载 作者:行者123 更新时间:2023-12-05 04:39:51 25 4
gpt4 key购买 nike

我正在尝试编写一个使用泛型和条件类型返回值的函数,如下所示:

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 })因为它还不知道用法。

Live example here

最佳答案

这是一个常见问题,泛型类型不会在函数实现内部解析。您可以编写一个函数重载来使您的实现工作:

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>
function createFoo({ withBar }: Options<boolean>): Foo<true> | Foo<false> {
// The implementation works because the return type is allowed to be Foo<true> or Foo<false>
return {
id: 'foo',
...(withBar && { bar: 'baz' }),
};
}

// The first function overload is taken because it's the first one to match
// the call parameters
const foo = createFoo({ withBar: false }); // foo is of type Foo<false>

TypeScript playground

关于typescript - 条件泛型的返回类型不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70383778/

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