簡體   English   中英

TypeScript:連接 arrays 與不同的元素類型

[英]TypeScript: concat arrays with different element-types

這是有效的。

let head = [["title", "value"], ["a", 1]];
let tail = [["b", 2], ["c", 3]];

let all = head.concat (tail);

好的結果是

[["title", "value"], ["a", 1], ["b", 2], ["c", 3]]

但我需要的是這個——那是行不通的。

let head = [["title", "value"]];
let tail = [["a", 1], ["b", 2], ["c", 3]];

let all = head.concat (tail);

錯誤:

Argument of type '(string | number)[][]' is not assignable to parameter 
of type 'string[] | string[][]'. 
 Type '(string | number)[][]' is not assignable to type 'string[][]'. 
  Type '(string | number)[]' is not assignable to type 'string[]'. 
   Type 'string | number' is not assignable to type 'string'. 
    Type 'number' is not assignable to type 'string'.

如果我將尾部的數字變為字符串,它會起作用 - 由於某些原因我不能這樣做。

那么我怎樣才能讓它工作呢?

謝謝!

您可以這樣聲明head的類型:

let head: [Array<string|number>] = [["title", "value"]];

這將消除錯誤,並保持類型安全性。

你可以這樣做: [].concat(head,tail)

const all = [...head, ...tail];

如果已經輸入了headtail

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM