javascript - TypeScript 联合类型问题
问题描述
我是 TypeScript 的新手。我正在尝试运行类似的场景,但它给出了两个错误。我不知道我在这里错过了什么。谁能帮我解决这个问题?
interface Foo {
[key: string]: number
};
interface Bar {
[key: string]: { positive: number, negative: number }
}
// const obj: Foo | Bar = {
// usa: { positive: 5, negative: 3 },
// uk: { positive: 4, negative: 1 },
// fr: { positive: 8, negative: 2 },
// }
const obj: Foo | Bar = {
usa: 5,
uk: 3,
fr: 2,
}
Object.keys(obj).map(key => {
const val = 'positive' in obj[key] ? obj[key].positive : obj[key];
alert(val);
})
我得到的两个错误是:
解决方案
您可以在此处使用用户定义的类型保护,让编译器知道您的检查应该缩小类型。这仅适用于变量而不是表达式,因此您必须先将其分配给单独的变量。
interface Foo {
[key: string]: number
};
interface PosNeg {
positive: number
negative: number
}
interface Bar {
[key: string]: PosNeg
}
type FooBar = Foo | Bar
type PossibleValues = FooBar[keyof FooBar]
function isPosNeg(item: PossibleValues): item is PosNeg {
return typeof item !== "number"
}
const obj: FooBar = {
usa: 5,
uk: 3,
fr: 2,
}
Object.keys(obj).map(key => {
const item = obj[key]
const val = isPosNeg(item) ? item.positive : item;
alert(val)
})
推荐阅读
- c# - 如何将标签中的信息导入 C# 和 HTMLAgilityPack?
- sql - 两列上的复合非空约束
- node.js - VSCode 不会关闭子进程 (processChild.js)
- java - Spark - 从列中读取 JSON 数组
- c# - 如何绑定分层列表
到 WPF 树视图 - javascript - 如何从对象数组中创建一串键值对对象?
- python - 为什么 subprocess.run 返回退出代码 2 但日志中没有错误?
- csv - Flink ParserError UNQUOTED_CHARS_AFTER_QUOTED_STRING
- python - PyTorch DataLoader 如何与 PyTorch 数据集交互以转换批次?
- javascript - 如何关闭 echarts 的自动放大功能?