Type casting in Typescript

Typecast types in Typescript. That’s three “types” in a sentence with three significant words, and for that, I tap out.

Typecasting exists where type don’t exist. In Typescript types are not “cast” into other types. Typescript supports a way for you the developer to override default type inference for neutral types like any.

And, we have discussed about type assertion before.

Type assertion is simple enough -

const clueless:unknown = "1";
const clueNum:number= <number>clueless;

// preferred format
const clueNumPreferred = clueless as number;

See the aforementioned article to know more.

But, what if you want to actually cast a variable declared as one type to another in Typescript?

Then, my friend, you want type conversions. That is fairly familiar territory by now -

const position: string = "3";

const posNum: number = Number(position);
console.log("posNum: ", posNum.toFixed(0));
// 3

.toFixed() is just to demonstrate that 3, the number, is indeed converted to '3', the string.

The same is applicable for any other types.

const answer = 42;
// auto inferred

const life = String(answer);
console.log("life: ", life.toLowerCase());
// 42
comments powered by Disqus