mattpocock / ts-reset

A 'CSS reset' for TypeScript, improving types for common JavaScript API's
https://www.totaltypescript.com/ts-reset
MIT License
7.9k stars 124 forks source link

Type `Array.includes` as a type guard #203

Open Danoha opened 2 months ago

Danoha commented 2 months ago

When checking that a variable is one of possible values, my team uses the following:

const status: 400 | 404 | 500;

if ([400, 404].includes(status)) {
  // status should be 400 | 404
}

Maybe we can add a type guard override for Array.includes such that when the second argument (fromIndex) is not specified, it tests that searchElement is one of the array values.

Something like:

interface ReadonlyArray<T> {
    includes(searchElement: unknown): searchElement is T;
    // ... default type
}

Is this feasible?

victorgarciaesgi commented 1 month ago

I dig this too! I though it was by default because otherwise it's not useful at all

victorgarciaesgi commented 1 month ago

Humm, answer here :( https://github.com/mattpocock/ts-reset/pull/130