简体   繁体   English

TypeScript 联合类型问题

[英]TypeScript Union Type Issue

I am new to TypeScript.我是 TypeScript 的新手。 I am trying to run a similar scenario but it is giving two errors.我正在尝试运行类似的场景,但它给出了两个错误。 I don't know what I am missing here.我不知道我在这里缺少什么。 Can anyone please help me to fix this issue?谁能帮我解决这个问题?

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

The two errors I am getting are:我得到的两个错误是:

在此处输入图像描述

在此处输入图像描述

You can use user defined type guards here to let the compiler know that your check is supposed to be narrowing down the type.您可以在此处使用用户定义的类型保护,让编译器知道您的检查应该缩小类型。 This only works on variables though and not expressions so you have to assign it to a separate variable first.这仅适用于变量而不是表达式,因此您必须先将其分配给单独的变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM