Typescript Examples: Type Casting and Type Conversions
Last updated:Table of Contents
Cast string to number
Same as Javascript, use parseInt()
const num = parseInt("45");
console.log(typeof num);
// 'number'
Cast number to string
Just use toString()
, but must assign to a variable first.
const num = 45
const numStr = num.toString();
console.log(typeof numStr);
// 'string'
Convert object to array of key-value objects
const peopleObj = {
john: {
name: "john",
age: 20
},
mary: {
name: "mary",
age: 22
}
}
const peopleArray = Object.keys(peopleObj).map(key => peopleObj[key]);
console.log(peopleArray);
// [ { name: 'john', age: 20 }, { name: 'mary', age: 22 } ]