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

2 minutes read

Typescript: cast an object to other type. How?

Use <> or the as keyword for casting:

var myObject: TypeA;
var otherObject: any;
// values are assigned to them, and...
myObject = <TypeA> otherObject;     // using <>
myObject = otherObject as TypeA;    // using as keyword

Both ways have the same (compile-time, not runtime) outcome.

Ok, both works the same, which one should I use, then? <> or as?

Since Typescript 1.6, the default is as, because <> is ambiguous in .jsx files. Click here for more details.

So… casting using as is preferred.

How about checking if an object is an instance of a given type?

Glad you asked. This shouldn’t come as a big surprise, though, instanceof in TypeScript is similar to other popular languages:

if (myObject instanceof Type) {
  console.log("myObject *is* an instance of Type!");
} else {
  console.log("Oops! myObject is not an instance of Type...");

You can find more about it in the TypeScript Language Specification:

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the ‘Function’ interface type. The result is always of the Boolean primitive type.

Note that object types containing one or more call or construct signatures are automatically subtypes of the ‘Function’ interface type, as described in section 3.3.

Great, but…

Since we’re at it, have you heard of the typeof operator?

Using the typeof operator, you can find out a variable’s type:

// Using typeof in an EXPRESSION:
var x = 5;  
var y = typeof x; // y will have the string "number" as value

// Using typeof in an TYPE QUERY
// (or... as I like to say, variable declaration):
var a = 9; // a is a number
var b: typeof a; // b will be declared as a number as well

b = "a string"; // yields an error, as b is a number:
                // "The type 'string' is not assignable to type 'number'."

Check a demo of the above code here.

Find more about typeof in the TypeScript spec as well.

That’s it.

Leave a Comment