我正在尝试使用元素数组作为联合类型,这在 TS 3.4 中使用 const 断言变得容易,所以我可以这样做:
const CAPITAL_LETTERS = ['A', 'B', 'C', ..., 'Z'] as const;
type CapitalLetter = typeof CAPITAL_LETTERS[string];
Run Code Online (Sandbox Code Playgroud)
现在我想测试一个字符串是否是大写字母,但以下失败并显示“不可分配给类型的参数”:
let str: string;
...
CAPITAL_LETTERS.includes(str);
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来解决这个问题,而不是投射CAPITAL_LETTERS到unknown然后到Array<string>?
老实说,我不知道我的设置是否有问题,或者这是否是打字稿功能。在以下示例中:
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)