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