![](/img/trans.png)
[英]Adding typescript tagged unions to result from graphql query in gatsby
[英]Is there a way to create tagged unions of arrays in TypeScript?
我正在嘗試使用標記的聯合在 TypeScript 中表示 arrays 的異構數組。
但是我不確定這在 TypeScript 中是否可行。
type Entity<K, V> = [number, K, V, number];
type All =
| Entity<"foo", number>
| Entity<"bar", string>
| Entity<"baz", string[]>;
const data: All[] = [
[1, "foo", 4, 12345],
[2, "bar", "hello world", 12346],
[3, "baz", ["New York", "Los Angeles"], 123457],
];
data.map((datum) => {
const [id, attr, val, tx] = datum;
switch (attr) {
case "foo":
return val + 1; // Operator '+' cannot be applied to types 'string | number | string[]' and 'number'.ts(2365)
case "bar":
return `The following is a string: '${val}'`;
case "baz":
return val.join(", "); // Property 'join' does not exist on type 'string | number | string[]'. Property 'join' does not exist on type 'string'.ts(2339)
}
});
TypeScript 不區分數組的第二個值來推斷第三個元素的類型。
這在表示為對象數組時有效,但不適用於 arrays。
元組類型可以是標記聯合的組成部分。 解構后的真正限制[id, attr, val, tx] = datum;
typescript 不會考慮以任何方式相關的解構變量,因此縮小一個不會影響其他變量。
如果您使用索引編寫代碼,則代碼按預期工作:
data.map((datum) => {
switch (datum[1]) {
case "foo":
return datum[2] + 1; // ✅
case "bar":
return `The following is a string: '${datum[2]}'`;
case "baz":
return datum[2].join(", "); // ✅
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.