tsafe
GitHub
  • 👋What is tsafe?
  • ⚙️How to import
  • assert
  • Equals
  • id
  • is
  • objectKeys
  • exclude
  • isAmong
  • symToStr
  • ReturnType
  • Parameters
  • Param0
  • typeGuard
  • capitalize/uncapitalize
  • MethodNames
  • isPromiseLike
  • flip
  • objectEntries
  • objectFromEntries
  • UnionToIntersection
  • 🚧withDefaults
  • 📉UnpackPromise
Powered by GitBook
On this page
  • Practical example
  • Basic examples

Was this helpful?

Edit on GitHub

exclude

Returns a function that you can use as the argument for Array.prototype.filter to exclude one or more primitive values from an array.

Practical example

import { exclude } from "tsafe/exclude";

type Circle = {
	type: "circle";
	radius: number;
};

type Square = {
	type: "square";
	sideLength: number;
};

type Shape = Circle | Square;

declare const shapes: Shape[];

//Assumes we want to do something for every Circle

shapes
	.map(shape => (shape.type === "circle" ? shape : null))
	.filter(exclude(null))
	.forEach(circle => {
		//Here circle is of type Circle
		//if we had used .filter(shape=> shape.type === "circle")
		//it would be functionally the same but circle would be of type
		//Shape
	});

Basic examples

import { exclude } from "tsafe/exclude";

const arr = ["a", "b", "c", "d"] as const;
const newArr = arr.filter(exclude("a"));

//type of newArr is ("b" | "c" | "d")[]
//value of newArr is ["b", "c", "d"]

You can also exclude more than on element:

import { exclude } from "tsafe/exclude";

const arr = ["a", "b", "c", "d"] as const;
const newArr = arr.filter(exclude(["a", "b"]));

//type of newArr is ("c" | "d")[]
//value of newArr is ["c", "d"]
PreviousobjectKeysNextisAmong

Last updated 5 months ago

Was this helpful?