简体   繁体   中英

Typescript nullable keys in object array type declaration

I'm using Typescript to write React Components. Currently I'm defining the types of props as 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 . In practice, the nullable name key works well for individual objects of type Prop . When declaring an object of type ParentProps this it gives shown in the snippet above.

For consistency with simpler components I would rather keep using type to define component props, rather than interface. 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.

Thank you.

What about define Props in following ways:

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 :

type ParentProps = Array< Omit<Props, "name"> & { name?: string|null } >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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