Cast an object to other type using Typescript. How? And instanceof or typeof?
Asked
Active
Viewed 1.1k times
10
-
Does this answer your question? [TypeScript or JavaScript type casting](https://stackoverflow.com/questions/13204759/typescript-or-javascript-type-casting) – Michael Freidgeim Jun 29 '20 at 11:56
2 Answers
1
"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

Saumyajit
- 678
- 8
- 10