【问题标题】:What should be the type of parameter in Typescript which take Array of Obj in a functional component TypescriptTypescript 中的参数类型应该是什么类型,它在功能组件 Typescript 中采用 Obj 数组
【发布时间】:2021-05-19 06:50:14
【问题描述】:
const Form = ({ arrayValue }: any): JSX.Element => {
console.log("Array of Obj",arrayValue)
//It is a form big form component....
});
arrayValue 是一个对象数组,其中项目的数量很大,我怎样才能删除 any 类型并为这些组件赋予特定类型?
【问题讨论】:
标签:
javascript
arrays
typescript
types
custom-data-type
【解决方案1】:
你有几种方法可以做到:
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 }
Playground
请记住,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