首页 > 解决方案 > 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);
})

我得到的两个错误是:

在此处输入图像描述

在此处输入图像描述

标签: javascripttypescript

解决方案


您可以在此处使用用户定义的类型保护,让编译器知道您的检查应该缩小类型。这仅适用于变量而不是表达式,因此您必须先将其分配给单独的变量。

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

推荐阅读