wat voor soort beweert heb ik nodig om dit te compileren?
class Foo {}
class Bar {}
var f =
[
[Foo, [1, 2, 3]],
[Bar, [7, 8, 9]],
];
fout:
Incompatible types in array literal expression
wat voor soort beweert heb ik nodig om dit te compileren?
class Foo {}
class Bar {}
var f =
[
[Foo, [1, 2, 3]],
[Bar, [7, 8, 9]],
];
fout:
Incompatible types in array literal expression
Dit zal werken:
class Foo {}
class Bar {}
var f: any[][] = [
[Foo, [1, 2, 3]],
[Bar, [7, 8, 9]],
];
Deze zegt dat je een twee-dimensionale array waarvan de waarden kan van alles (Foo, Bar, andere arrays, etc). U kunt ook gebruik maken van een soort verklaring voor uw geneste arrays:
class Foo {}
class Bar {}
var f = [
[<any>Foo, [1, 2, 3]],
[<any>Bar, [7, 8, 9]],
];
De aanwezigheid van een eventuele in de binnenreeks dwingt de compiler het type af te leiden als alle [].
Het lijkt erop dat typoscript doet hebben heterogene arrays nu. Dus, omdat deze vraag kwam voor het eerst toen ik keek voor dit, en omdat het moeilijk is om het anders te vinden, hier hoe deze code kan nu geschreven worden:
class Foo {}
class Bar {}
var f: [Foo|Bar, number[]][] =
[[new Foo(), [1, 2, 3]],
[new Bar(), [7, 8, 9]]];
(Nu, als dit gaat op de weg van het type syntaxis nabootsen van uitdrukkingen, het type zou ook een syntaxis van [Foo|Bar, [...number]][]...)
Het werkt zelfs met de functie argumenten, dus dit typechecks prima:
function foo([obj,nums]: [Foo|Bar, number[]]) {
for (let i of nums) console.log(`i = ${i}`);
}
f.forEach(foo);
en de extreme versie:
f.forEach(([obj,nums]: [Foo|Bar, number[]]) => {
for (let i of nums) console.log(`i = ${i}`); });
Vanaf Typescript 1.4 kunt u het type vakbonden doen. Ik was in staat om dit te bereiken als volgt:
function zip<T, X> (array1: T[], array2: X[]): (T|X)[][] {
return array1.map(function (v: T, i: number) { return [v, array2[i]]; });
}
Het specifieke type zou je zoekt in uw geval zou zijn:
(Foo|Bar|number[])[][]
Of:
(typeof Foo|typeof Bar|number[])[][]