You are here: Home / Topics / TypeCasting in Typescript

TypeCasting in Typescript

Filed under: TypeScript on 2024-03-18 11:11:32

TypeScript supports typecasting, which allows you to explicitly change the type of a value. There are following ways to perform typecasting in TypeScript: using the as keyword and using angle bracket syntax (<>).


In TypeScript, assertion and typecasting are often used interchangeably, but they have slightly different connotations. Here's a breakdown of the two concepts:


Assertion (or Type Assertion):


An assertion is a way to inform the TypeScript compiler about the type of a value. 
It is typically used when you have more knowledge about the type than TypeScript's type inference can determine.
The purpose of assertion is to explicitly tell the compiler to treat a value as a specific type, even if it doesn't match the inferred or
declared type.
It is performed using the as keyword or angle bracket syntax (<>).
An assertion doesn't perform any runtime type checking or conversion; it's a compile-time construct.


Typecasting:


Typecasting refers to the actual process of converting an object or value from one type to another.
It involves changing the underlying representation of a value to another type.
Typecasting is common in languages like C or C++, where you can explicitly convert between types (e.g., casting an integer to a float).
In TypeScript, typecasting is not as expected because the language is statically typed and focuses on type safety.
While the as keyword and angle bracket syntax (<>) are often called typecasting, they are actually forms of assertion rather than true typecasting.

In summary, an assertion in TypeScript is a compile-time construct used to inform the compiler about the type of a value, whereas typecasting refers to converting a value from one type to another. TypeScript's assertion, using as or angle brackets, is more about type information rather than actual runtime conversion.


Note: TypeScript allows you to override its inferred and analyzed view of types in any way you want to. This is done by a mechanism called "type assertion". TypeScript's type assertion is purely you telling the compiler that you know about the types better than it does, and that it should not second guess you.

Example 1: Find the string length by assertion any to string


index.ts:
let value: unknown = "Hello, TypeScrip!";
let len = (value as string).length;
console.log(len);
console.log(typeof value);

Note: if line number 2: value as string will be written as value only, it will show an error. Execute the tsc index.ts --target es2015 command to compile typescript code, then execute the code using the node index.js command.


Example 2: <> brackets


index.ts:
let value: any = "Hello, TypeScrip!";
let len = (<string>value).length;
console.log(len);
console.log(typeof value);
Note: Execute the tsc index.ts --target es2015 command to compile typescript code, then execute the code using the node index.js command.

Example 3: Any vs Unknown


index.ts:
let vAny: any = 10; // We can assign anything to any

let vUnknown: unknown = 10; // We can assign anything to unknown just like any
let s1: string = vAny; // Any is assignable to anything
let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion)
vAny.method(); // Ok; anything goes with any
vUnknown.method(); // Not ok; we don't know anything about this variable

 
Note: Execute the tsc index.ts --target es2015 command to compile typescript code, then execute the code using the node index.js

Example 4: What is actually assertion? 


index.ts:
//Case one: Output Error because “132”
let value1: unknown = "132";
//use Number(value1) or can use other ways for type conversion
let num1 = <number>value1;
console.log(typeof num1);
let result = num1 + 99;
console.log(result);//output: string 13299
//Case two: No output error because the actual number 45 (type unknown) changes to a number.
let value: unknown = 45;
value = (value as number) + 9;
console.log(value);
Note: This example shows in Case One that by writing line number 2 (<number>value1) not converting unknown (by default string) to number. So, there is no runtime effect of type assertion in TypeScript. It is merely a way to let the TypeScript compiler know the type of a variable.
In the second case, the unknown refers to the number by default and the assertion confirms to the compiler that the value 45 is a number.

Execute the tsc index.ts --target es2015 command to compile typescript code, then execute the code using the node index.js command.


Example 5: Type Assertion with Object


let employee = { };
employee.name = "John"; //Compiler Error: Property 'name' does not exist on type '{}'
employee.code = 123; //Compiler Error: Property 'code' does not exist on type '{}'


Example 6: Type Assertion with Object


class Employee {// The class must change to interface.
name: string;
code: number;
}

let employee = <Employee> { };
employee.name = "John"; // OK
employee.code = 123; // OK
console.log(employee);

About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.