繁体   English   中英

Typescript object 数组类型声明中的可空键

[英]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' 

在这种情况下,我希望ParentProps type只是Props type的数组。 在实践中,可为空的名称键适用于Prop类型的单个对象。 当声明一个ParentProps类型的 object 时,它给出了上面的代码片段。

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

谢谢你。

如何通过以下方式定义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 } >

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM