Doesn't this error defeat the purpose of using Array.prototype.includes()?
Not really. It's just TypeScript doing its job: making the code typesafe. You've said that arr can only include the values 0 or 1, so calling includes with a value that can't be in the array is a type error. (That said, I could definitely see an argument for includes to accept number instead of 0 | 1 in a case like that. I suspect there are counter-arguments though.)
You could write a utility function to check if a number is a valid element for arr:
const isValidArrElement = (value: number): value is Arr[number] => {
return value === 0 || value === 1;
};
Then use that before using includes:
const arr: Arr = [0, 1]
const someNumber: number = 5;
if (isValidArrElement(someNumber) && arr.includes(someNumber)) {
// ...
}
Playground link
But I usually prefer to approach this the other way so that I'm not writing the 0 and 1 in two places and creating a maintenance hazard:
const validArrElements = [0, 1] as const;
type ArrElement = (typeof validArrElements)[number];
// ^? -- type is 0 | 1
const isValidArrElement = (value: number): value is ArrElement => {
return (validArrElements as readonly number[]).includes(value);
};
Note that isValidArrElement does have a type assertion in it. I'm not bothered about that, because I only do this in these pairs of things (constant arrays of valid values and type checkers for them).
The usage is the same as above:
const arr: Arr = [0, 1]
const someNumber: number = 5;
if (isValidArrElement(someNumber) && arr.includes(someNumber)) {
// ...
}
Playground link
Arror doing some type casting?" as stated on the question.