type narrowing in typescript based on enum in type

  Kiến thức lập trình

say for example I have this type in typescript:

enum NumberOrStringType {
    NUMBER,
    STRING,
}

type NumberOrString = {
    dataType: NumberOrStringType,
    data: string | number;
};

and later in the code:

const numOrString: NumberOrString = { dataType: NumberOrStringType.NUMBER, data: 10 };

if (numOrString.dataType === NumberOrStringType.NUMBER) {
    const num: number = numOrString.data;
    ... 
} else {
    const str: string  numOrString.data;
    ...
}

Unfortunately, I get errors saying that type string | number is not assignable to type number and type string | number is not assignable to type string.

I know I can just cast num and str by using as number and as string respectively, but is there a way to tell typescript to determine the type of data via the enum is has been assigned, or by narrowing the type by using an if statement?

LEAVE A COMMENT