Skip to content

Instantly share code, notes, and snippets.

@alii
Last active October 14, 2021 13:16
Show Gist options
  • Save alii/eae7de6127284c1423188303b7db2319 to your computer and use it in GitHub Desktop.
Save alii/eae7de6127284c1423188303b7db2319 to your computer and use it in GitHub Desktop.
Checks if a value exists in an array in a type safe manner
/**
* Checks if a value exists in an array in a type safe manner
* @param value Value to check
* @param arr An array of possible matches
* @returns A boolean indicating if a passed value is one of the items in the array
*/
export function is<V extends string | number, Arr extends readonly [V, ...V[]]>(
value: unknown,
arr: Arr,
): value is Arr[number] {
return arr.includes(value as V);
}
// Playground: https://www.typescriptlang.org/play?#code/KYDwDg9gTgLgBAMwK4DsDGMCWEV0wZwB4A1OUGYFAE3znxikxQHM4AfOFJAWwCNgoAGjgBBKFDIgK1WlGABDKjgA2ATzgBtYsIB0e4hoC6hgHwAKALAAoAJAA3ecqTAAXHFQBrFBADuKQdY28uJuYkLWAJRuDk7AeLRhGlx8AoZwAN6BcjBIULjBUDpMaE5UwPhmMc5w8rTEEQDc1gC+1tYA9O1wAMK18DAQcAAGtXQMTMxDcANkULVxAOQAFsDKgz7QylQL06pgwDrWaDj0cFVxALxwy6vrm9s1tPSMLE1W1pgIcGYElY7Owg0NzWcA2UC2C2EwJBYIhhgiEQygU6Z3+cQIdHkCFW6hge2AVDgKzkLTIynwcUythR53inGAmBgxJaQA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment