是否可以仅使用类型来推断值的通用类型?
例如类型:
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)