我希望我的函数返回嵌套类型的内容,但即使我们确定应该返回的类型它也不起作用。我们来看看例子:
type Content = {
some: {
extra: string;
prop: number;
},
other: string,
somenumber: number
}
const factory = (content: Content) => {
return (key: keyof Content) => {
return content[key];
};
};
const content:Content = {
some: {
extra: "wow",
prop: 123
},
other: "abc",
somenumber: 999
};
const el = factory(content);
const some = el("some"); // good, I can pass only existing key as a string
console.log(some.extra); // error, can't reach "extra"
我希望“some”包含并提出“extra”和“prop”,但采取“extra”会抛出TypeScript。
使用泛型类型参数定义函数,以便Typescript可以正确推断类型:
const factory = (content: Content) => {
return <K extends keyof Content>(key: K) => {
return content[key];
};
};
修复非常简单:
const factory = (content: Content) => {
return <T extends keyof Content>(key: T) => {
return content[key];
};
};
不同的是,现在我们将key
的类型限制为传递字符串文字而不是任何Content
密钥