javascript - Typescript 中的参数类型应该是什么类型,它在功能组件 Typescript 中采用 Obj 数组
问题描述
const Form = ({ arrayValue }: any): JSX.Element => {
console.log("Array of Obj",arrayValue)
//It is a form big form component....
});
arrayValue
是一个对象数组,其中项目的数量很大,如何删除任何类型并为这些组件赋予特定类型?
解决方案
你有几种方法可以做到:
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
推荐阅读
- augmented-reality - 考虑到用户体验,什么是 AR 应用的最佳设备(手机或平板电脑)?
- microsoft-graph-api - Graph ODATA $filter startswith 函数不适用于 Sharepoint 中的列表项
- amazon-web-services - 是否可以在 yml 中为 AWS ECS 指定 sourcePath?
- php - php stream_socket_client 第一次调用耗时太长
- encryption - OpenEBS 是否支持静态加密?
- python - tkinter 保持句柄活着
- python - python:如何计算一行的元素?
- postman - 邮递员 - 无法从属性键中具有 `:` 的对象获取值
- html - HTML CSS hover 改变两个元素
- scala - Spark中两个任务之间的时间间隔