【问题标题】:Why typescript can't infer the generic type by its fields?为什么打字稿不能通过其字段推断泛型类型?
【发布时间】:2022-09-29 21:37:56
【问题描述】:

我不明白为什么有时打字稿无法推断出 const 的泛型类型。

这是一个例子:

type OneTwoThree = 1 | 2 | 3;

type MyType<num extends OneTwoThree> = {
    n: num;
}

const first: MyType = { // <-- Generic type \'MyType\' requires 1 type argument(s).(2314)
    n: 2,
};

const second: MyType<3> = {
    n: 3,
};

为什么打字稿不能推断firstMyType&lt;2&gt; 类型?

我也尝试过以这种方式声明MyType

type MyType<num extends OneTwoThree = OneTwoThree> = {
    n: num;
}

但是这样首先变成const first: MyType&lt;OneTwoThree&gt;类型...

这是游乐场链接:https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gdhAKgdwPaIBYCcLQLxQCMUAPlAEylQDMA3AFD2iRQCyIi4EAPHAK4BbKBAAewCHAAmAZ1gIU6bLigF4SNJhwQAfCqgBvelGNQ4ALlOCGAX0YBjVHGnAoAMwCWWZxfacWBQxNTC3IAGnprBnoHJxdpCBjJHw4ubmpdAKMTcxpwyKA

有什么建议么?

  • 它无法推断,因为它会模棱两可。在first 中,缺少的类型参数可能是2OneTwoThree,两者都是有效的。唯一合理的选择是提供默认类型或自己指定。

标签: typescript typescript-generics


【解决方案1】:

你可以用一个函数来做到这一点:

function foo<T extends OneTwoThree>(param: T): MyType<T> {
    return { n: param }
}

const bar = foo(3); //  MyType<number>
const baz = foo(3 as const); //  MyType<3>

Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2019-04-10
    • 1970-01-01
    • 2021-03-10
    • 2020-12-17
    相关资源
    最近更新 更多