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

如何定义可包含iFormInputTest对象与嵌套数组的TypeScript类型?

解决TypeScript混合数组元素类型定义问题

问题根源

你当前定义的data: iFormInputTest[] | iFormInputTest[][]是整个数组的类型二选一:要么是只包含iFormInputTest对象的一维数组,要么是只包含iFormInputTest[]的二维数组。但你的实际数据是一维数组,其中每个元素可以是iFormInputTest对象或iFormInputTest[]数组,两种类型不匹配,因此报错。

正确类型定义

将data的类型改为(iFormInputTest | iFormInputTest[])[],表示数组中的每个元素既可以是单个对象,也可以是对象数组:

export type iFormInputTest = {
  name: string
  type: 'textInput' | 'Select'
}

export type iFormInputsTest= {
  button: {
    label: string
    style?: { [key: string]: any }
  }
  // 修改这里的类型定义
  data: (iFormInputTest | iFormInputTest[])[]
}

const inputs: iFormInputsTest = {
  button: {
    label: 'Submit'
  },
  data: [
    {
      name: 'input1',
      type: 'textInput'
    },
    [
      {
        name: 'input2',
        type: 'textInput'
      },
      {
        name: 'input3',
        type: 'Select'
      }
    ],
    {
      name: 'input4',
      type: 'textInput'
    }
]}

优化写法(可选)

如果需要提升代码可读性,可以提前定义元素类型:

type FormInputItem = iFormInputTest | iFormInputTest[]
export type iFormInputsTest= {
  button: {
    label: string
    style?: { [key: string]: any }
  }
  data: FormInputItem[]
}

内容的提问来源于stack exchange,提问作者Mertafor

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:25:24