Search code examples
reactjstypescriptnullabletyping

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.


Solution

  • 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 } >