I honestly don't know if something is wrong with my settings or of if this is a typescript feature. In the following example:
type AllowedChars = 'x' | 'y' | 'z';
const exampleArr: AllowedChars[] = ['x', 'y', 'z'];
function checkKey(e: KeyboardEvent) {
if (exampleArr.includes(e.key)) { // <-- here
// ...
}
}
The typescript compiler complains that Argument of type 'string' is not assignable to parameter of type 'AllowedChars'. But where am I assigning? Array.prototype.includes returns a boolean (which I am not storing). I could silence the error by a type assertion, like this:
if (exampleArr.includes(e.key as AllowedChars)) {}
But how is that correct, I am expecing user input which could be anything. I don't understand why a function (Array.prototype.includes()) made to check if an element is found in an array, should have knowledge about the type of input to expect.
My tsconfig.json (typescript v3.1.3):
{
"compilerOptions": {
"target": "esnext",
"moduleResolution": "node",
"allowJs": true,
"noEmit": true,
"strict": true,
"isolatedModules": true,
"esModuleInterop": true,
"jsx": "preserve",
},
"include": [
"src"
],
"exclude": [
"node_modules",
"**/__tests__/**"
]
}
Any help would be appreciated!
.includes(), you're effectively assigninge.keyto the parameter. You declared the array as being an array of theAllowedCharstype, ande.keyis not of that type.exampleArr as string[]?