Home > Net >  Set all optional (question mark) types of an interface as never in Typescript
Set all optional (question mark) types of an interface as never in Typescript

Time:06-15

I want to know if there is a way I can create a generic type (something like NeverOptionals<T>) such that I can make all optional types on an interface never (kind of similar to Required<T> but not quite the same).

For example for the following interface:

interface Foo {
    a?: string;
    b: number;
    c: string | undefined;
    d?: number | undefined;
}

Using NeverOptionals<Foo> would be equivalent to the following interface:

interface FooNeverOptionals {
    a?: never;
    b: number;
    c: string | undefined;
    d?: never;
}

CodePudding user response:

For your question, you can try the following codes. But { key?: never } will also be asserted to { key: undefined }, so I am not sure this is your want.

Typescript Playground

type NeverOptionals<T> = {
  [P in keyof T]: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : never;
}

If your purpose is to exclude the optional keys, you can try this.

Typescript Playground


interface Foo {
  a?: string;
  b: number;
  c: string | undefined;
  d?: string;
}

type NeverOptionals<T> = {
  [P in keyof T]-?: Pick<T, P> extends Required<Pick<T, P>> ? T[P] : never;
}

type ExcludeNever<T> = { [P in keyof T as T[P] extends never ? never : P]: T[P] };


type ExcludOptionals<T> = ExcludeNever<NeverOptionals<T>>

type T1 = ExcludOptionals<Foo>
//   T1 = { b: number; c: string | undefined; } 


Hope it can help you.

  • Related