Syntax

TypeScript Custom Type Guard Syntax

In TypeScript, custom type guard: writes a function that narrows a type — function isFish(p: Fish | Bird): p is Fish { return "swim" in p; }

Quick Answer

Syntax
function isFish(p: Fish | Bird): p is Fish { return "swim" in p; }
TypeScriptSyntax

Custom Type Guard

Code example
function isFish(p: Fish | Bird): p is Fish { return "swim" in p; }

Writes a function that narrows a type.

Learn More

How to custom type guard in TypeScript

  1. Open your TypeScript file or editor.
  2. Copy the example, then replace its sample names and values for your code.

TypeScript Custom Type Guard Syntax

Use function isFish(p: Fish | Bird): p is Fish { return "swim" in p; }.

Related Syntax References

Frequently asked questions

What is the TypeScript syntax for custom type guard?

Use this pattern: function isFish(p: Fish | Bird): p is Fish { return "swim" in p; }

Can I copy this TypeScript code example?

Yes. Use Copy code and adapt the example to your program.

Is this TypeScript syntax different on Mac or Windows?

No. The language syntax is the same across operating systems.

Official source · How we verify