is is meant to be used in conjunction with assert and enable you to tell the compiler:

"Trust me this value is of type T" or "Trust me this value is not of type T"

import { assert } from "tsafe/assert";
import { is } from "tsafe/is";

type Circle = { radius: number };
type Square = { sideLength: number };
type Shape = Circle | Square;

declare const shape: Shape;

//You: Trust me TypeScript, I know that shape is a Circle.

//TypeScript: Ok if you say has a radius then.

Equally useful you can tell TypeScript that your shape is not a Square, it will infer that, it is then a Circle.

//You: Trust me TypeScript, I know that shape is not a Square.

//TypeScript: Ok so by elimination it should be a Circle!

is must always be used in conjunction with assert as described in the example above.

You aren't even allowed to do something like assert(is<Circle>(shape) && shape.radius > 100 )

For any other use case considertypeGuard instead.

It is important to understand that here that when you run the instruction assert(typeGuard<Circle>(shape)) if the shape happens not to be a Circle you won't get an error at runtime.

Last updated