首页 > 解决方案 > 将接口定义为具有给定对象的所有键

问题描述

我正在编写一些看起来像这样的代码:

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示例中),打字稿不会警告我。

我将如何更改我的代码来实现这一目标?

标签: typescript

解决方案


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)'

希望这可以帮到你


推荐阅读