如何定义可包含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
相关产品推荐
相关产品推荐

