如何在TypeScript中迭代已知值类型的对象?

db2dz4w8  于 2022-12-19  发布在  TypeScript
关注(0)|答案(1)|浏览(112)

我有一本来自API的UI更改字典:

interface UIChangesDictionary {
    christmasTreeCount: number;
    greeting: string;
    isDarkMode: boolean;
}

让我们使用静态对象来简化操作:

const changes: UIChangesDictionary = {
    christmasTreeCount: 14,
    greeting: "Ho ho ho",
    isDarkMode: true,
};

现在,在我的API处理程序中,我想迭代这些更改并应用适当的UI更改:

Object.entries(changes).forEach(
    ([ property, value ]) => {
        switch (property) {
            case "christmasTreeCount":
                // value should be number
                break;
            case "greeting":
                // value should be string
                break;
            case "isDarkMode":
                // value should be boolean
                break;
        }
    }
);

不幸的是,value总是any,我以为Object.entries()能够正确地推断类型,但它不能。
如何实现它,使value使用其接口中的类型?

xjreopfe

xjreopfe1#

  • 可以使用类型Assert或类型graud。
Object.entries(changes).forEach(([property, value]) => {
  const change = value as UIChangesDictionary;
  switch (property) {
    case 'christmasTreeCount':
      // value should be number
      console.log(change);
      break;
    case 'greeting':
      console.log(change);
      break;
    case 'isDarkMode':
      console.log(change);
      break;
  }
});

或类型Grad。

Object.entries(changes).forEach(([property, value]) => {
  switch (property) {
    case 'christmasTreeCount':
      if (typeof value === 'number') {
        const count = value;
        console.log(count);
      }
      break;
    case 'greeting':
      break;
    case 'isDarkMode':
      break;
  }
});

相关问题