【发布时间】:2019-08-12 20:31:55
【问题描述】:
似乎将输入 arg 推断为通用索引签名并没有按预期工作(或者我完全遗漏了什么????)。
如何推断返回类型并正确验证输入?
interface Styles {
contentAlign?: string;
zIndex?: number;
}
function createTheme<S extends { [key: string]: Styles }>(theme: S) {
return theme;
}
// this works, foo is marked as invalid
const style: Styles = {
zIndex: 1,
foo: 'bar', // <-- invalid
};
// once I try to use the Styles as index signature it allows other properties
const t = createTheme({
Button: {
zIndex: 1,
foo: 'bar', // <-- valid??
},
});
我期待Type { foo: "bar" } is not assignable to type Styles,但它似乎是一个有效的输入
【问题讨论】:
-
我想完成那个变量
t具有传入的对象的推断类型:js { Button: { zIndex: number } }
标签: typescript typescript-generics