gpt4 book ai didi

TypeScript:无法编写异构数组文字

转载 作者:搜寻专家 更新时间:2023-10-30 20:32:23 24 4
gpt4 key购买 nike

我需要什么类型的断言才能编译?

class Foo {}
class Bar {}

var f =
[
[Foo, [1, 2, 3]],
[Bar, [7, 8, 9]],
];

错误:

Incompatible types in array literal expression

最佳答案

这会起作用:

class Foo {}
class Bar {}

var f: any[][] = [
[Foo, [1, 2, 3]],
[Bar, [7, 8, 9]],
];

这表示您有一个二维数组,其值可以是任何值(Foo、Bar、其他数组等)。您还可以为嵌套数组使用类型断言:

class Foo {}
class Bar {}

var f = [
[<any>Foo, [1, 2, 3]],
[<any>Bar, [7, 8, 9]],
];

内部数组中单个 any 的存在迫使编译器将其类型推断为 any[]。

关于TypeScript:无法编写异构数组文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12715909/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com