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?
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) }
You'll need to make any optional properties in your interface defined as such:
type gridProps = {
itemsArrayFiltered: object[],
cardWidth?: number, // optional
cardHeight: number
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With