write a type predicate in typescript

In TypeScript, you can write a type predicate by using the is keyword. A type predicate is a function that takes an input parameter and returns a type assertion that the input parameter is of a specific type.

Here's an example of how you can write a type predicate in TypeScript:

index.ts
function isNumber(value: unknown): value is number {
  return typeof value === "number";
}
91 chars
4 lines

In the above example, the isNumber function is a type predicate that takes an unknown parameter and asserts that it is of type number. The value is number syntax is used to provide type information to the TypeScript compiler.

You can then use this type predicate to perform type narrowing in conditional statements or type guards:

index.ts
function double(value: unknown): number | null {
  if (isNumber(value)) {
    return value * 2;
  }
  return null;
}
117 chars
7 lines

In the double function, the isNumber type predicate is used to narrow the type of the value parameter to number before multiplying it by 2. If the isNumber predicate returns true, the code within the if block is executed, otherwise it returns null.

Using type predicates can help you write more type-safe code in TypeScript by narrowing the type of variables based on runtime checks.

Note: Type predicates can only be used with type assertions, not type annotations. The is keyword can only be used within the body of a function or method.

related categories

gistlibby LogSnag