如何迭代对象知道值类型在TypeScript?



我有一个来自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使用类型从它的接口?

  • 可以使用类型断言或类型分级。
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;
}
});

或类型

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;
}
});

相关内容

  • 没有找到相关文章

最新更新