【发布时间】:2020-07-10 03:35:39
【问题描述】:
考虑一下:
type SpecificKeys<T extends string> = {
[key in T]: string;
};
const foobar: SpecificKeys<"foo" | "bar"> = {
foo: "foo",
bar: "bar",
};
在创建foobar 时,我必须将键的并集指定为泛型类型参数,这是多余的。我想不出任何办法。但是如果我写一个无所事事的函数:
function makeSpecificKeys<T extends string>(thing: SpecificKeys<T>): SpecificKeys<T> {
return thing;
}
const foobarInferred = makeSpecificKeys({
foo: "foo",
bar: "bar",
});
那么 const foobarInferred 被正确输入为 SpecificKeys<"foo" | "bar"> 并且我不必通过枚举所有键来重复自己。
有没有什么方法可以在创建类型化变量时实现泛型类型参数的推断,而不必做一个无所事事的函数?
【问题讨论】:
标签: typescript typescript-generics