问题描述
我正在使用Typescript编写React组件。
目前,我将道具的类型定义为Typescript type
。
这是一个示例:
type Props = {
id: number //required
name: string | null //optional
}
type ParentProps = Array<Props>
let props:ParentProps = [
{
id:5,name:"new"
},{
id:7,}
]
//Gives error: Property 'name' is missing in type '{ id: number; }' but required in type 'Props'
在这种情况下,我希望type
ParentProps
只是type
Props
的数组。实际上,可为空的名称键对于类型为Prop
的单个对象非常有效。声明类型为ParentProps
的对象时,它会显示在上面的代码片段中。
为了与更简单的组件保持一致,我宁愿继续使用type
来定义组件道具,而不是接口。对于如何获取声明类型以定义允许某些空键的类型对象数组的人,会有任何建议。
谢谢。
解决方法
如何通过以下方式定义Props
:
type Props = {
id: number
name?: string | null
}
或者只是
type Props = {
id: number
name?: string
}
此外,如果您希望保持Props
的定义不变,则可以更改type ParentProps
:
type ParentProps = Array< Omit<Props,"name"> & { name?: string|null } >