How can I achieve this ?
type Fruit = "apple" | 'banana' | 'coconut'
type FruitCollection = { [f in Fruit]?: number }
const validFruitCollection: FruitCollection = { apple: 1, coconut: 2 }
const emptyCollectionShouldNotPass: FruitCollection = {} // I don't want typescript to let this pass
You can intersect the type with all optional members with a union of all properties, where all in each constituent of the union, one member is required. So basically you will have:
To get this type without writing it out we can use a mapped type:
Playground Link
The idea of the mapped type in
RequireOne
is to create union in theWhatWeWant
type above (T
will be the original type will al the optional properties). So what we do, in the mapped type is we take each property inT
and type it asRequired<Pick<T, P>>
. This means for each key, we get a type that only contains that key, basically this type for the example:With this type, the matter of getting the union we want is just a matter with indexing
keyof T
, to get a union of all property types in our object.What we need is type which will exclude possibility of empty object. In order to achieve that we need utility type and value constructor. Consider: