Make some properties optional in a TypeScript type

You can use combination of Partial and Pick to make all properties partial and then pick only some that are required:

interface SomeType {
    prop1: string;
    prop2: string;
    prop3: string;
    propn: string;
}

type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> & Pick<T, TRequired>

type NewType = OptionalExceptFor<SomeType, 'prop1' | 'prop2'>

let o : NewType = {
    prop1: "",
    prop2: ""
}

For tetter performance, in addition to Titian's answer, you must do :

type OptionalExceptFor<T, TRequired extends keyof T = keyof T> = Partial<
  Pick<T, Exclude<keyof T, TRequired>>
> &
  Required<Pick<T, TRequired>>;

type onlyOneRequired = Partial<Tag> & {id: string}

In the above type, all properties of Tag are optional instead of id which is required. So you can use this method and specify the required properties.

Tags:

Typescript