Make some of the type's field optional

33 Views Asked by At

I have an interface

interface I1 {
 field1: fieldType1;
 ...
 fieldN: fieldTypeN;
}

Now, I need an interface that has the same fields, but some of them (say the first 10) are optional.

I can write it as Omit<I1, field1, ..., field 10> & {field1?: fieldType1 ...} but wonder if there is a more concise way to do it.

There are similar questions that are focused on making 1 field optional, the key here is to do it for multiple (large number) of fields.

1

There are 1 best solutions below

0
Arkerone On BEST ANSWER

You can create a utility type like this:

type PartialKeys<T, K extends keyof T> = Partial<Pick<T, K>> & Omit<T, K>;

And use it like this :

type I2 = PartialKeys<I1, 'field1' | 'field2'>

You can't easily "say I want the first N items" because TypeScript's type system doesn't support enforcing order in an object's properties