连接两个Array <[''string','string']>会引发编译器警告

时间:2019-07-11 17:04:24

标签: typescript

我试图像这样加入两个数组:

const param = null
const optionsHeaders: Array<['string', 'string']> = param || []
const sesHeaders = [
    ['X-SES-CONFIGURATION-SET', 'config-set']
]
const headers: Array<['string', 'string']> = [...optionsHeaders, ...sesHeaders]
console.log(headers)

结果符合预期:

[
  [
    "X-SES-CONFIGURATION-SET",
    "config-set"
  ]
]

但是TypeScript编译器在抱怨:

Type 'string[][]' is not assignable to type '["string", "string"][]'.
  Type 'string[]' is missing the following properties from type '["string", "string"]': 0, 1

const headers: Array<['string', 'string']> = [...optionsHeaders, ...sesHeaders]

我在这里想念什么?

1 个答案:

答案 0 :(得分:3)

您需要sesHeaders上的类型,因为默认情况下,数组文字[ 'foo', 'bar']的推断类型为string[]而不是[string, string]

此外,您的'string'不需要单引号,因为正如@ n​​ino-filio所指出的,常量值也可以是类型,因此说'string'就是说“仅字符串值“字符串””。

type Headers = [ string, string ][];

const param = null
const optionsHeaders: Headers = param || []
const sesHeaders: Headers = [
    ['X-SES-CONFIGURATION-SET', 'config-set']
]
const headers: Headers = [...optionsHeaders, ...sesHeaders]
console.log(headers);