简体   繁体   中英

TypeScript Union Type Issue

I am new to 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)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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