如何在 TypeScript 中循环元组数组?例如
for (const [x, y] of [['a', 1], ['b', 2]]) {
y + 1;
}
Run Code Online (Sandbox Code Playgroud)
抱怨:
error TS2365: Operator '+' cannot be applied to types 'string | number' and '1'.
Run Code Online (Sandbox Code Playgroud)
如果我理解正确的话,TypeScript 会推断(string | number)[][]循环表达式的类型,这就是为什么循环变量y具有类型string | number,尽管实际上它只能具有类型number?
我认为https://github.com/microsoft/TypeScript/issues/3369是阻止 TypeScript 推断合适类型的问题。循环元组数组的当前解决方案是什么?类型断言?
如何在 TypeScript 中编写泛型类型谓词?
\n\n在下面的示例中,if (shape.kind == \'circle\')不会将类型缩小为Shape<\'circle\'>//Circle{ kind: \'circle\', radius: number }
interface Circle {\n kind: \'circle\';\n radius: number;\n}\n\ninterface Square {\n kind: \'square\';\n size: number;\n}\n\ntype Shape<T = string> = T extends \'circle\' | \'square\'\n ? Extract<Circle | Square, { kind: T }>\n : { kind: T };\n\ndeclare const shape: Shape;\nif (shape.kind == \'circle\') shape.radius;\n// error TS2339: Property \'radius\' does not exist on type \'{ kind: string; }\'.\nRun Code Online (Sandbox Code Playgroud)\n\n我尝试编写一个泛型类型谓词来解决此问题,但以下内容不起作用,因为类型参数在运行时不可用
\n\nfunction …Run Code Online (Sandbox Code Playgroud) typescript ×2