映射类型:删除可选修饰符 [英] Mapped Types: removing optional modifier

查看:23
本文介绍了映射类型:删除可选修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此代码:

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

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

我希望 Foo2 的类型是 { one: number;二:数量;} 然而,它似乎保留了可选的修饰符 { one?: number;二?:数;}

I would expect the type of Foo2 to be { one: number; two: number; } However, instead it seems to keep the optional modifier { one?: number; two?: number; }

使用映射类型时是否可以删除可选修饰符?

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

推荐答案

在 Typescript 2.8 中,您可以显式消除修饰符:

In Typescript 2.8 you can explicitly eliminate the modifier:

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

或者使用新版本中内置的 Required 类型.

Or use the Required type that 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>;

这篇关于映射类型:删除可选修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆