Sometimes, you must check whether a value is of a certain type. For instance, if you have a value of a class Base
, you might want to check if it is of a certain subclass Derived
. In JavaScript you would write this with an instanceof
check. Since TypeScript is an extension of JavaScript, you can also use instanceof
in TypeScript. In other typed languages, like C#, you must then add a type cast, which tells the compiler that a value is of a type, different from what the compiler analyzed. You can also add type casts in two different ways. The old syntax for type casts uses <
and >
, the new syntax uses the as
keyword. You can see them both in the next example:
class Base { a: string; } class Derived extends Base { b: number; } const foo: Base; if (foo instanceof Derived) { (<Derived> foo).b; (foo as Derived).b; }
When you use a type guard, you say to the compiler: trust me, this value will...