简体   繁体   English

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

[英]Typescript nullable keys in object array type declaration

I'm using Typescript to write React Components.我正在使用 Typescript 来编写 React 组件。 Currently I'm defining the types of props as Typescript type .目前我将道具类型定义为 Typescript type Here's an example:这是一个例子:

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' 

In this case I would like for the type ParentProps to be just an array of the type Props .在这种情况下,我希望ParentProps type只是Props type的数组。 In practice, the nullable name key works well for individual objects of type Prop .在实践中,可为空的名称键适用于Prop类型的单个对象。 When declaring an object of type ParentProps this it gives shown in the snippet above.当声明一个ParentProps类型的 object 时,它给出了上面的代码片段。

For consistency with simpler components I would rather keep using type to define component props, rather than interface.为了与更简单的组件保持一致,我宁愿继续使用type来定义组件道具,而不是接口。 Would anyone have any advice on how to get declare a type to define an array of types objects that allow for certain null keys.有人对如何声明类型以定义允许某些 null 键的类型对象数组有任何建议吗?

Thank you.谢谢你。

What about define Props in following ways:如何通过以下方式定义Props

type Props = {
  id: number
  name?: string | null
}

or just要不就

type Props = {
  id: number
  name?: string
}

Also, if you want to leave Props definition unchanged, you can change type ParentProps :此外,如果您想保持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