0

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:

enter image description here

enter image description here

1 Answer 1

2

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)
})
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help. The answer is wrong. I have fixed it. isPosNeg function should return the following -- return item.positive !== undefined;
Ah yeah, my bad. Probably makes much more sense here to only allow the possible values for the objects and check to make sure that the type isn't a number. This way the code breaks as expected when you change the values of either of those types, I've edited my answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.