我正在写一些看起来像这样的代码:
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
示例中),打字稿不会警告我。
我将如何更改代码以实现这一目标?
答案 0 :(得分:2)
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)'
希望这可以为您提供帮助