Link to minimum reproducible example: https://tsplay.dev/mL90eW
I have this data shape that I want to enforce in TypeScript to following requirements
- Must have first field that want to call
valueLabel
(YearQtr here) - Must have at least one of other three fields that I want to call
nameLabel
(House, Unit, Land)
const data: [
{ YearQtr: '2000Q1', House: '100', Unit: '200', Land: '300' },
{ YearQtr: '2000Q2', Unit: '400' },
{ YearQtr: '2000Q4', House: '500', Land: '600' },
{ YearQtr: '2001Q2', Unit: '700', Land: '800' },
I have defined a type for it in TypeScript but this allows wrong entries in as well (see the last three rows in example below:
type StackbarDatum = {
[key: string]: string
}
const data: StackbarDatum[] = [
{ YearQtr: '2000Q1', House: '100', Unit: '200', Land: '300' },
{ YearQtr: '2000Q2', Unit: '400' },
{ YearQtr: '2000Q4', House: '500', Land: '600' },
{ YearQtr: '2001Q2', Unit: '700', Land: '800' },
{ YearQtr: '2002Q1', House: '900', Unit: '1000' },
{ }, // this should not be allowed
{ YearQtr: '2002Q1' }, // this should not be allowed
{ House: '900', Unit: '1000' }, // this should not be allowed
]
I want to know how to do it properly in Type Safe way.