-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
TypeScript 之映射类型 #230
Labels
Comments
This was referenced Dec 7, 2021
Open
// 当你需要提前声明属性的类型时 const conforms: OnlyBoolsAndHorses = { |
type ExtractPII<Type> = {
[Property in keyof Type]: Type[Property] extends { pii: boolean } ? true : false;
};
type DBFields = {
id: { format: "incrementing" };
name: { type: string; pii: true };
comment: { type: string; pii: false };
};
type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;
// type ObjectsNeedingGDPRDeletion = {
// id: false;
// name: true;
// comment: true;
// } |
翻译错了,原文是根据pii是否设置为true返回true false |
typescript面向类型编程 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
映射类型(Mapped Types)
有的时候,一个类型需要基于另外一个类型,但是你又不想拷贝一份,这个时候可以考虑使用映射类型。
映射类型建立在索引签名的语法上,我们先回顾下索引签名:
而映射类型,就是使用了
PropertyKeys
联合类型的泛型,其中PropertyKeys
多是通过keyof
创建,然后循环遍历键名创建一个类型:在这个例子中,
OptionsFlags
会遍历Type
所有的属性,然后设置为布尔类型。映射修饰符(Mapping Modifiers)
在使用映射类型时,有两个额外的修饰符可能会用到,一个是
readonly
,用于设置属性只读,一个是?
,用于设置属性可选。你可以通过前缀
-
或者+
删除或者添加这些修饰符,如果没有写前缀,相当于使用了+
前缀。通过
as
实现键名重新映射(Key Remapping viaas
)在 TypeScript 4.1 及以后,你可以在映射类型中使用
as
语句实现键名重新映射:举个例子,你可以利用「模板字面量类型」,基于之前的属性名创建一个新属性名:
你也可以利用条件类型返回一个
never
从而过滤掉某些属性:你还可以遍历任何联合类型,不仅仅是
string | number | symbol
这种联合类型,可以是任何类型的联合:深入探索(Further Exploration)
映射类型也可以跟其他的功能搭配使用,举个例子,这是一个使用条件类型的映射类型,会根据对象是否有
pii
属性返回true
或者false
:TypeScript 系列
TypeScript 系列文章由官方文档翻译、重难点解析、实战技巧三个部分组成,涵盖入门、进阶、实战,旨在为你提供一个系统学习 TS 的教程,全系列预计 40 篇左右。点此浏览全系列文章,并建议顺便收藏站点。
微信:「mqyqingfeng」,加我进冴羽唯一的读者群。
如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎 star,对作者也是一种鼓励。
The text was updated successfully, but these errors were encountered: