1

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.

1 Answer 1

2

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 } >
Sign up to request clarification or add additional context in comments.

1 Comment

This goes in the right direction, optional properties are indeed written with a ?, but null should be removed from the type in this case. An optional property will never evaluate to null unless it was explicitly set to null, in which case the optionality of the property isn't relevant since it was specified. In other words, your second version is proper.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.