首页 > 解决方案 > Typescript 中的参数类型应该是什么类型,它在功能组件 Typescript 中采用 Obj 数组

问题描述

const Form = ({ arrayValue }: any): JSX.Element => {
    console.log("Array of Obj",arrayValue)
    
    //It is a form big form component....
});

arrayValue是一个对象数组,其中项目的数量很大,如何删除任何类型并为这些组件赋予特定类型?

标签: javascriptarraystypescripttypescustom-data-type

解决方案


你有几种方法可以做到:

import React, { FC } from 'react'

type Obj = {
  name: string
}

type Props = {
  arrayValue: Obj[]
}

const Form: FC<Props> = ({ arrayValue }) => {
  console.log("Array of Obj", arrayValue)
  const x = arrayValue[0].name // ok
  return <div></div>

  //It is a form big form component....
};

// OR GENERIC WAY

const Form2 = <T,>({ arrayValue }: { arrayValue: T[] }) => {
  console.log("Array of Obj", arrayValue)
  return <div></div>

  //It is a form big form component....
};
type Obj2 = { age: number }

操场

请记住,generic way有自己的缺点。您不能引用数组中特定元素的属性,但可以为T参数提供一些限制(界限)。

例如:


const Form2 = <T extends { age: number }>({ arrayValue }: { arrayValue: T[] }) => {
  console.log("Array of Obj", arrayValue)
  arrayValue[0].age // ok
  return <div></div>

  //It is a form big form component....
};
type Obj2 = { age: number }

const result = <Form2<Obj2> arrayValue={[{ age: '42' }]} /> // error, because age ahouls be a number

推荐阅读