A common problem faced with using Array.includes() in TypeScript:
const environments = ["DEV", "UAT", "PROD"] as const;
function isSupported(env: string) {
if (environments.includes(env)) {
// Error: Argument of type 'string' is not
// assignable to parameter of type '"DEV" | "UAT" | "PROD"'.
}
}
TypeScript narrow Array.includes()
A common problem faced with using
Array.includes()in TypeScript:The definition of
Array.includes():The function wants both the searchElement and the array to be of the same type.
This can be solved by narrowing the type using a helper function:
ReadonlyArray<T>and search for element of typeU.T extends U: T is a subset of U.searchElement is T.