相关疑难解决方法(0)

为什么 Array.prototype.includes(searchElement) 的参数需要与数组元素的类型相同?

老实说,我不知道我的设置是否有问题,或者这是否是打字稿功能。在以下示例中:

type AllowedChars = 'x' | 'y' | 'z';
const exampleArr: AllowedChars[] = ['x', 'y', 'z'];

function checkKey(e: KeyboardEvent) { 
    if (exampleArr.includes(e.key)) { // <-- here
        // ...
    } 
}
Run Code Online (Sandbox Code Playgroud)

打字稿编译器抱怨Argument of type 'string' is not assignable to parameter of type 'AllowedChars'.但是我在哪里分配?Array.prototype.includes返回一个布尔值(我没有存储)。我可以通过类型断言消除错误,如下所示:

if (exampleArr.includes(e.key as AllowedChars)) {}
Run Code Online (Sandbox Code Playgroud)

但这如何正确,我期待用户输入可能是任何内容。我不明白为什么一个函数(Array.prototype.includes())以检查是否一个元素在数组中发现,有关于输入的期望类型的知识。

我的tsconfig.json(打字稿 v3.1.3):

 {
    "compilerOptions": {
      "target": "esnext",
      "moduleResolution": "node",
      "allowJs": true,
      "noEmit": true,
      "strict": true,
      "isolatedModules": true,
      "esModuleInterop": true,
      "jsx": "preserve",
    }, …
Run Code Online (Sandbox Code Playgroud)

javascript typescript

3
推荐指数
1
解决办法
1155
查看次数

标签 统计

javascript ×1

typescript ×1