I have an array as const:
const array = ['a', 'b'] as const;
Now I want to check if a value is in that array:
let variable = 'a';
if (array.includes(variable))
Typescript yields an error:
TS2345: Argument of type string is not assignable to parameter of type ‘a’ | ‘b’
Which is correct. But how can I avoid it? I found the solutions:
if (array.includes(variable as typeof array[number]))
if ((array as unknown as string[]).includes(variable))
But both are not satisfying me because they are pretending something that is not true.
Does anybody know a better solution?
1
- typing
variable
as const
will infer that it’s of type'a'
, and thus compatible with the array - you don’t need 15 casts,
array
is a readonly array, so you need to cast it to that e.g.array as readonly string[]
1
Use as const might not be flexible for array value. Maybe do like this instead
type Data = 'a' | 'b';
const array: Data[] = ['a', 'b'];
const variable = 'a';
if (array.includes(variable)) {
// do something
}
Or
const array: string[] = ['a', 'b'];
const variable = 'a';
if (array.includes(variable)){
// do something
}