Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructuring properties with default values in Typescript

Let's say I have a type defined like this:

type gridProps = {
  itemsArrayFiltered: object[],
  cardWidth: number,
  cardHeight: number
}

And I have a React component like this:

const Grid = 
  ({ itemsArrayFiltered, cardWidth = 280, cardHeight }: gridProps) => 
(whatever)

If I do not provide the cardWidth property in the type gridProps, then I get the error message:

Property 'cardWidth' does not exist on type 'gridProps'.ts(2339)

That is correct but, the question is: Should it not be enough to provide the default value 280? I feel I am duplicating code by providing a number default value and also writing number in the type gridProps. Is there a better way to avoid this?

like image 876
fjplaurr Avatar asked Feb 25 '26 04:02

fjplaurr


2 Answers

Well, I understand that you want TS to infer cardWidth property type but without having to declare the property for your Type. In this case you will have to tell TS that you're type has a property cardWidth since Object literals undergo excess property checking. As how you should/could do this, @aWolf mention that you could make cardWidth optional:

 type gridProps = {
  itemsArrayFiltered: object[],
  cardWidth?: number,
  cardHeight: number,
}

you could also use an intersection if you want to leave the Type lean:

type gridProps = {
  itemsArrayFiltered: object[],
  cardHeight: number,
}

const Grid = ({ cardHeight, cardWidth = 280, itemsArrayFiltered }: GridProps & { cardWidth?: number }) { (whatever) }
like image 78
theFreedomBanana Avatar answered Feb 26 '26 17:02

theFreedomBanana


You'll need to make any optional properties in your interface defined as such:

type gridProps = {
  itemsArrayFiltered: object[],
  cardWidth?: number, // optional
  cardHeight: number
}
like image 33
3066d0 Avatar answered Feb 26 '26 18:02

3066d0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!