首页 > 解决方案 > 对象数组类型声明中的打字稿可为空的键

问题描述

我正在使用 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. 在实践中,可为空的 name 键适用于类型为 的单个对象Prop。当声明一个ParentPropsthis 类型的对象时,它给出了上面的代码片段。

为了与更简单的组件保持一致,我宁愿继续使用type来定义组件道具,而不是接口。有人对如何声明类型以定义允许某些空键的类型对象数组有任何建议吗?

谢谢你。

标签: reactjstypescriptnullabletyping

解决方案


如何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 } >

推荐阅读