I know it is an old question but I'm not satisfied by the other answers. Please avoid the as
keyword as much as possible !
Let's see why we encounter this error and what to do with it.
Reason : neither the const nor the array of strings have a type.
When you do not give a type to a const, Typescript infers its type based on the initial value. Knowing that, the error just says "hey, e
could be any string, even strings that are not part of the inferred type of your const". What if e
was equal to 'yellow'
that is not known in color
inferred type ?
I can recommend you 3 ways to handle this :
1. Simplest but not so "Typescript Spirit" solution
Just give a type string
to the keys of your const, like this :
const color: {[key:string]:null} = {
red: null,
green: null,
blue: null
};
Hmmm... That works, but we can do better.
2. On the way to types...
Tell Typescript compiler you are using the keys of the inferred type of the const with the keywords : keyof typeof
.
In the given example, that would be :
const colorKeys: (keyof typeof color)[] = ['red', 'green', 'blue'];
const newColor = colorKeys.filter((e) => color[e]);
Can you still make a little extra effort? See next point.
3. Here it is : give types to your objects !
Create an interface (or whatever you need as a type) and give it to your const. Then, specify the type of the array of strings with the keyof
keyword :
interface Color {
red:number|null;
green:number|null;
blue:number|null;
}
const color: Color = {
red: null,
green: null,
blue: null
};
const colorKeys: (keyof Color)[] = ['red', 'green', 'blue'];
const newColor = colorKeys.filter((e) => color[e]);