对象数组类型声明中的打字稿可空键
Typescript nullable keys in object array type declaration
我正在使用 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 } >
我正在使用 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 } >