how to use the without function from the underscore library in typescript

To use the without function from the Underscore library in TypeScript, you first need to install the Underscore library via an NPM package. Here are the basic steps:

  1. Install the Underscore library as an NPM package:
index.ts
npm install underscore
23 chars
2 lines
  1. Import the Underscore library and the without function in your TypeScript module:
index.ts
import * as _ from 'underscore';

// ...

const myArray: number[] = [1, 2, 3, 4, 5];

// Remove the values 2 and 4 from the array
const newArray: number[] = _.without(myArray, 2, 4);

console.log(newArray); // Output: [1, 3, 5]
228 chars
11 lines

Note that without returns a new array with the specified values removed. It does not modify the original array.

One thing to note is that if you want to use without with a generic array type (e.g. Array<T> or T[]), you may see TypeScript compiler errors around the types of the values being passed to without. To fix this, you can use a type assertion to tell TypeScript the specific type of the array elements:

index.ts
const myArray: Array<Person> = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];

// Remove the person with name 'Bob' from the array
const newArray: Array<Person> = _.without(
  myArray,
  <Person>{ name: 'Bob', age: 25 } as Person
);

console.log(newArray); // Output: [{ name: 'Alice', age: 30 }, { name: 'Charlie', age: 35 }]
374 chars
14 lines

In this example, the Person interface is defined as:

index.ts
interface Person {
  name: string;
  age: number;
}
52 chars
5 lines

gistlibby LogSnag