小编not*_*rig的帖子

TypeScript 循环元组数组

如何在 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

11
推荐指数
2
解决办法
7932
查看次数

TypeScript 泛型类型谓词

如何在 TypeScript 中编写泛型类型谓词?

\n\n

在下面的示例中,if (shape.kind == \'circle\')不会将类型缩小为Shape<\'circle\'>//Circle{ kind: \'circle\', radius: number }

\n\n
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; }\'.\n
Run Code Online (Sandbox Code Playgroud)\n\n

我尝试编写一个泛型类型谓词来解决此问题,但以下内容不起作用,因为类型参数在运行时不可用

\n\n
function …
Run Code Online (Sandbox Code Playgroud)

typescript

11
推荐指数
1
解决办法
8503
查看次数

标签 统计

typescript ×2