typescript - 将接口定义为具有给定对象的所有键
问题描述
我正在编写一些看起来像这样的代码:
interface Config {
[key: string]: number;
}
interface Foo {
value: number;
}
interface ConfiguredObject {
[key: string]: Foo;
}
function createConfiguredObject(config: Config): ConfiguredObject {
return Object.entries(config).reduce((acc, cur) => {
return {
...acc,
[cur[0]]: {
value: cur[1] * 10
}
};
}, {});
}
const myObject = createConfiguredObject({
foo: 1,
bar: 2
});
console.log(myObject.foo.value); //No warning
console.log(myObject.charlie.value); //No warning, but will throw an error
console.log(myObject.foo.aaa); //'Property 'aaa' does not exist on type 'Foo'.ts(2339)'
https://codesandbox.io/s/loving-taussig-88try
也就是说 - 我想将一个Config
对象传递给一个函数,然后让该函数返回一个具有匹配键和某些值的对象。
我目前拥有的问题是,如果我尝试访问不存在的密钥(在myObject.charlie
示例中),打字稿不会警告我。
我将如何更改我的代码来实现这一目标?
解决方案
interface Config {
[key: string]: number;
}
interface Foo {
value: number;
}
type ConfiguredObject<T> = {
[key in keyof T]: Foo;
}
function createConfiguredObject<T extends Config>(config: T): ConfiguredObject<T> {
return Object.entries(config).reduce((acc, cur) => {
return {
...acc,
[cur[0]]: {
value: cur[1] * 10
}
};
}, {} as ConfiguredObject<T>);
}
const myObject = createConfiguredObject({
foo: 1,
bar: 2
});
console.log(myObject.foo.value); //No warning
console.log(myObject.charlie.value); //Property 'charlie' does not exist on type 'ConfiguredObject<{ foo: number; bar: number; }>'.
console.log(myObject.foo.aaa); //'Property 'aaa' does not exist on type 'Foo'.ts(2339)'
希望这可以帮到你
推荐阅读
- c++ - 具有不变和普通 typedef 的 typedef 有什么不同
- php - 如何使用 API 资源更改 json 格式?
- azure - Azure 队列存储消息未保存在 Azure 函数上的正确队列中
- testing - 如何使用jmeter执行存储过程并获得结果
- android - kotlin (Android Studio 3) 中未解析的引用 getValue()
- vbscript - vbs中的特殊字符
- reactjs - Redux 没有将状态传递给道具
- javascript - 扩展功能标签
- javascript - Node JS 中的文件下载
- python - 在 Python 3 中将阿拉伯语单词导出到 csv