Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: can't write heterogeneous array literals

Tags:

typescript

what type asserts do i need to get this to compile?

class Foo {}
class Bar {}

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

error:

Incompatible types in array literal expression
like image 707
Spongman Avatar asked Oct 03 '12 19:10

Spongman


1 Answers

This will work:

class Foo {}
class Bar {}

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

This says you have a two-dimensional array whose values can be anything (Foo, Bar, other arrays, etc). You could also use a type assertion for your nested arrays:

class Foo {}
class Bar {}

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

The presence of a single any in the inner array forces the compiler to infer its type as any[].

like image 90
Brian Terlson Avatar answered Oct 10 '22 19:10

Brian Terlson