Type Guard

Type Guards allow you to narrow down the type of an object within a conditional block.

typeof

TypeScript is aware of the usage of the JavaScript instanceof and typeof operators. If you use these in a conditional block, TypeScript will understand the type of the variable to be different within that conditional block. Here is a quick example where TypeScript realizes that a particular function does not exist on string and points out what was probably a user typo:

  1. function doSomething(x: number | string) {
  2. if (typeof x === 'string') { // Within the block TypeScript knows that `x` must be a string
  3. console.log(x.subtr(1)); // Error, 'subtr' does not exist on `string`
  4. console.log(x.substr(1)); // OK
  5. }
  6. x.substr(1); // Error: There is no guarantee that `x` is a `string`
  7. }

instanceof

Here is an example with a class and instanceof:

  1. class Foo {
  2. foo = 123;
  3. common = '123';
  4. }
  5. class Bar {
  6. bar = 123;
  7. common = '123';
  8. }
  9. function doStuff(arg: Foo | Bar) {
  10. if (arg instanceof Foo) {
  11. console.log(arg.foo); // OK
  12. console.log(arg.bar); // Error!
  13. }
  14. if (arg instanceof Bar) {
  15. console.log(arg.foo); // Error!
  16. console.log(arg.bar); // OK
  17. }
  18. console.log(arg.common); // OK
  19. console.log(arg.foo); // Error!
  20. console.log(arg.bar); // Error!
  21. }
  22. doStuff(new Foo());
  23. doStuff(new Bar());

TypeScript even understands else so when an if narrows out one type it knows that within the else it’s definitely not that type. Here is an example:

  1. class Foo {
  2. foo = 123;
  3. }
  4. class Bar {
  5. bar = 123;
  6. }
  7. function doStuff(arg: Foo | Bar) {
  8. if (arg instanceof Foo) {
  9. console.log(arg.foo); // OK
  10. console.log(arg.bar); // Error!
  11. }
  12. else { // MUST BE Bar!
  13. console.log(arg.foo); // Error!
  14. console.log(arg.bar); // OK
  15. }
  16. }
  17. doStuff(new Foo());
  18. doStuff(new Bar());

in

The in operator does a safe check for the existance of a property on an object and can be used as a type guard. E.g.

  1. interface A {
  2. x: number;
  3. }
  4. interface B {
  5. y: string;
  6. }
  7. function doStuff(q: A | B) {
  8. if ('x' in q) {
  9. // q: A
  10. }
  11. else {
  12. // q: B
  13. }
  14. }

Literal Type Guard

When you have literal types in a union you can check them to discriminate e.g.

  1. type Foo = {
  2. kind: 'foo', // Literal type
  3. foo: number
  4. }
  5. type Bar = {
  6. kind: 'bar', // Literal type
  7. bar: number
  8. }
  9. function doStuff(arg: Foo | Bar) {
  10. if (arg.kind === 'foo') {
  11. console.log(arg.foo); // OK
  12. console.log(arg.bar); // Error!
  13. }
  14. else { // MUST BE Bar!
  15. console.log(arg.foo); // Error!
  16. console.log(arg.bar); // OK
  17. }
  18. }

User Defined Type Guards

JavaScript doesn’t have very rich runtime introspection support built in. When you are using just plain JavaScript Objects (using structural typing to your advantage), you do not even have access to instanceof or typeof. For these cases you can create User Defined Type Guard functions. These are just functions that return someArgumentName is SomeType. Here is an example:

  1. /**
  2. * Just some interfaces
  3. */
  4. interface Foo {
  5. foo: number;
  6. common: string;
  7. }
  8. interface Bar {
  9. bar: number;
  10. common: string;
  11. }
  12. /**
  13. * User Defined Type Guard!
  14. */
  15. function isFoo(arg: any): arg is Foo {
  16. return arg.foo !== undefined;
  17. }
  18. /**
  19. * Sample usage of the User Defined Type Guard
  20. */
  21. function doStuff(arg: Foo | Bar) {
  22. if (isFoo(arg)) {
  23. console.log(arg.foo); // OK
  24. console.log(arg.bar); // Error!
  25. }
  26. else {
  27. console.log(arg.foo); // Error!
  28. console.log(arg.bar); // OK
  29. }
  30. }
  31. doStuff({ foo: 123, common: '123' });
  32. doStuff({ bar: 123, common: '123' });