Displayed Types: Removing Optional Modifier

Given this code:

interface Foo{
  one?: string;
  two?: string;
}

type Foo2 = {
  [P in keyof Foo]: number;
}

I would expect the type to Foo2be. { one: number; two: number; }However, it retains an optional modifier instead.{ one?: number; two?: number; }

Is it possible to remove an optional modifier when using mapped types?

+6
source share
2 answers

In Typescript 2.8, you can explicitly exclude the modifier:

type Foo2 = {
  [P in keyof Foo]-?: number;
}

Or use a type Requiredthat is built into newer versions.

If you are using an older version, you can use this workaround:

type Helper<T, TNames extends string> = { [P in TNames]: (T & { [name: string]: never })[P] };
type Foo3 = Helper<Foo, keyof Foo>;
+12
source

You can use Required<T>as an alternative-?

interface Foo {
  one?: string;
  two?: string;
}

type Foo2 = {
  [P in keyof Required<Foo>]: number;
};
+4
source

Source: https://habr.com/ru/post/1695768/


All Articles