Typescript assign a variable of multi type containing OR ( | ) to single type variable

Viewed 352

I have a variable that has type of number or string. How can I assign its value to a variable that accepts number only?

const id:Record<string, string|number> = {name:3}
let num: Record<string, number>;

num = id; //Shows error here

I know there can be javascript work arounds like writing a conversion function, but I am learning Typescript and want to know if there are keywords or typescript specific solutions that are meant to be used in such cases, like as Record<string,number>... that can cast it, instead of type assertion

Here is a link to the code on Typescript playground

4 Answers

It looks like you already answered your question, you can cast with the as keyword.

num = id as number

If you wanted to get fancy you could check the id's type with typeof so something like this

if (typeof id === 'number') {
  number = id
}

You can use TypeScript 3.7's Assertion Functions, to enforce the checks in the code that didn't eliminated the wrong type:

const id:Record<string, string|number> = {name:"3"}
let num: Record<string,string>;

//the code logic safely leads to this line only if "id" contains a number value

declare function isNumId(id: Record<string, string | number>): asserts id is Record<string, string>;

isNumId(id);
num = id; // No longer shows error here

Of course, it might be simpler to just tell TS that we are sure of the type:

num = id as Record<string, string>; // No longer shows error here

The Typescript playground link is bit different than what's in the question:

    const id:Record<string, string|number> = {name:"3"}
    let num: Record<string,string>;

    //the code logic safely leads to this line only if "id" contains a number value

    num = id; //shows error here

But anyway, there are two quick ways to deal with it:

    //One solution:
    
    const id2:Record<string, string> | Record<string,number> = {name:"3"}
    let num2: Record<string,string>;    
    num2 = id2;


    //Antoher solution:

    const id3:Record<string, string|number> = {name:"3"}
    let num3: Record<string,string>;
    num3 = id as Record<string,string>; 

https://www.typescriptlang.org/play?#code/LAKAkAxg9gdgzgFwAQEsAmAuASgU2gJzQB5F8UYBzAGiVPIoB8YBXAWwCMd8A+JAXiQBvGAENWODACIAzJIC+oMABscyFqwxJcBYnUpU9FbgG5QigPTmEACxxJoaO0qgUUEWiIBmOJQE8kKiJocEgIUKHWKCFK5HawfqieSJLokvawCCLkISJI6pz4SABuIkrMOGbg6vyoaMZIlnDWUADuIVz4UIW2+BUglWCWAPIwdnBQZQgosBiKitDwyOgATNh4XboIZPq0W-S8DFrrhCR7+vlcvALCYhIy8ooqamyrRzqn29SGJmCK6ss1FamfogwbmACCMDCPVoE2YUxmAwWiFq0jW70MNEMTDYBSuQlE4iksgU4CeeTYaLeGw+9AMZyMwLA6mkgLQSBEIW0NMx33qlSAA

Just use Number().

TypeScript provides static type checking, but those types don't have any effect at runtime. Doing something like as asserts to TypeScript about a variable's type, but it will not actually perform a "cast." If you want your string to be parsed into a number, this will not work.

Related