Define an object with an optional amount of keys,

2020-07-23 07:01发布

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

标签: typescript
2条回答
疯言疯语
2楼-- · 2020-07-23 07:37

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:


type WhatWeWant = {
    apple?: number | undefined;
    banana?: number | undefined;
    coconut?: number | undefined;
} & (
    | { apple: number; }
    | { banana: number; }
    | { coconut : number ;})

To get this type without writing it out we can use a mapped type:


type RequireOne<T> = T & { [P in keyof T]: Required<Pick<T, P>> }[keyof T]
type FruitCollection = RequireOne<{ [f in Fruit]?: number }>

Playground Link

The idea of the mapped type in RequireOne is to create union in the WhatWeWant 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 in T and type it as Required<Pick<T, P>>. This means for each key, we get a type that only contains that key, basically this type for the example:

{
  apple: { apple: number; }
  banana: { banana: number; }
  coconut: { coconut: number ;}
}

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.

查看更多
▲ chillily
3楼-- · 2020-07-23 07:53

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:

type Fruit = "apple" | 'banana' | 'coconut'

type FruitCollection = { [f in Fruit]?: number }

// type which will exclude empty object
type NotEmpty<T> = {} extends T ? never : T

// value constructor
const makeFruitCollection = <T extends FruitCollection>(c: NotEmpty<T>) => c; 

// use cases
const validFruitCollection = makeFruitCollection({ apple: 1, coconut: 2 }) // ok                                                                     
查看更多
登录 后发表回答