小编Tza*_*fil的帖子

有没有一种方法可以在不使用函数的情况下推断泛型类型

是否可以仅使用类型来推断值的通用类型?

例如类型:

interface MyType<T extends string> {
    foo: Record<T, any>,
    bar: Record<string, T>
}
Run Code Online (Sandbox Code Playgroud)

您可以使用函数推断泛型:

function typed<T extends string>(val: MyType<T>) {
    return val;
}
// Works! no typescript diagnostics.
typed({
    foo: { a: null, b: null },
    bar: { whatever: 'a' }
}) // expect MyType<'a'|'b'>
Run Code Online (Sandbox Code Playgroud)

是否存在无需函数即可推断的纯类型语法?(当然,没有在泛型中指定类型参数)

// Does not work! (Generic type 'MyType<T>' requires 1 type argument(s).)
const myType: MyType = {
    foo: { a: null, b: null },
    bar: { whatever: 'a' }
}
Run Code Online (Sandbox Code Playgroud)

generics type-inference typescript

18
推荐指数
1
解决办法
1万
查看次数

标签 统计

generics ×1

type-inference ×1

typescript ×1