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,string>
... that can cast it, instead of type assertion
Here is a link to the code on Typescript playground
CodePudding user response:
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
}
CodePudding user response:
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.