You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中string[] | number[]与(string | number)[]的区别?

TypeScript两种数组类型定义的区别

先明确两种接口定义的核心差异:

第一种定义:string[] | number[]

interface A {
  type: string[] | number[]
}

这里的type只能是纯字符串数组或者纯数字数组,二选一,数组里不能同时存在字符串和数字元素。

举个例子:

  • 合法赋值:
    const obj1: A = { type: ["vue", "react"] } // 纯字符串数组
    const obj2: A = { type: [1, 2, 3] } // 纯数字数组
    
  • 非法赋值(会触发类型报错):
    const obj3: A = { type: ["vue", 2] } // 混合字符串和数字,不符合类型要求
    

第二种定义:(string | number)[]

interface A {
  type: (string | number)[]
}

这里的type是元素为字符串或数字的数组,数组里可以同时包含两种类型的元素,纯字符串/纯数字数组也完全符合要求。

举个例子:

  • 合法赋值:
    const obj4: A = { type: ["vue", 2] } // 混合类型数组
    const obj5: A = { type: ["react", "angular"] } // 纯字符串数组
    const obj6: A = { type: [4, 5, 6] } // 纯数字数组
    

核心总结

  • string[] | number[]:数组本身的类型二选一,要么全是字符串,要么全是数字,绝对不能混合。
  • (string | number)[]:数组的每个元素类型二选一,单个元素可以是字符串或数字,数组内允许两种类型混合。

内容的提问来源于stack exchange,提问作者Alex Alan Nunes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 18:44:59