Typescript: Cast an object to other type using. How? And instanceof or typeof?

Something like this:

let object = myObject as string; // this way
let object = <string> myObject; // or this way

In addition, instanceof returns a boolean, typeof returns the instance type.


"Type Assertion" as this is called in Typescript can be done as follows:

interface Student {   
    name: string;   
    code: number;   
}  
let student = <Student> { }; //or { } as student
student.name = "Rohit"; // Correct  
student.code = 123; // Correct  

In the above example, we have created an interface Student with the properties name and code. Then, we used type assertion on the student, which is the correct way to use type assertion.

Use typeof for simple built in types:

true instanceof Boolean; // false
typeof true == 'boolean'; // true

Use instanceof for complex built in types:

[] instanceof Array; // true
typeof []; //object

Tags:

Typescript