[TypeScript] Transform Existing Types Using Mapped Types in TypeScript
Mapped types are a powerful and unique feature of TypeScript's type system. They allow you to create a new type by transforming all properties of an existing type according to a given transformation function. In this lesson, we'll cover mapped types like Readonly<T>
or Partial<T>
that ship with the TypeScript compiler, and we'll also explore how to create our own type transformations.
There are few mapped types built-in:
/**
* Make all properties in T optional
*/
type Partial<T> = {
[P in keyof T]?: T[P];
}; /**
* Make all properties in T readonly
*/
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}; /**
* From T pick a set of properties K
*/
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
}; /**
* Construct a type with a set of properties K of type T
*/
type Record<K extends string, T> = {
[P in K]: T;
};
Take readonly as an example, the output is like this:
interface Point {
x: number;
y: number;
}
ReadonlyPoint = Readonly<Point>; type ReadonlyPoint = {
readonly x: number;
readonly y: number;
}
So for each props in Point, we append 'readonly' type for it.
The way type resolve:
interface Point {
x: number;
y: number;
} // From
type ReadonlyPoint = {
readonly [P in keyof Point]: Point[P]
} type ReadonlyPoint = {
readonly [P in "x" | "y"]: Point[P]
} type ReadonlyPoint = {
readonly x: Point["x"];
readonly y: Point["y"];
} // To
type ReadonlyPoint = {
readonly x: number
readonly y: number;
}
The same process can be done with Partial type:
type PartialPoint = Partial<Point>; // From
type PartialPoint = {
[P in keyof T]?: T[P];
} type PartialPoint = {
[P in keyof Point]?: Point[P];
} type PartialPoint = {
[P in "x" | "y"]?: Point[P];
} type PartialPoint = {
x?: Point["x"];
y?: Point["y"];
} // To
type PartialPoint = {
x?: number;
y?: number;
}
We can also write Nullable type by ourselves:
type Nullable<T> = {
[P in keyof T]: T[P] | null
}
For each Prop fo Type T, it can be its value or null.
We can also combine different type together:
type Nullable<T> = {
[P in keyof T]: T[P] | null
} type Stringify<T> = {
[P in keyof T]: string
} type NullablePoint = Nullable<Point>
type PartialNullablePoint = Partial<Nullable<Stringify<Point>>>
[TypeScript] Transform Existing Types Using Mapped Types in TypeScript的更多相关文章
- [TypeScript] Type check JavaScript files using JSDoc and Typescript 2.5
Typescript 2.5 adds JSDoc type assertion support for javascript file via ts-check service. First of ...
- [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript
TypeScript’s discriminated union types (aka tagged union types) allow you to model a finite set of a ...
- [TypeScript] Union Types and Type Aliases in TypeScript
Sometimes we want our function arguments to be able to accept more than 1 type; e.g. a string or an ...
- [TypeScript] Dynamically Allocate Function Types with Conditional Types in TypeScript
Conditional types take generics one step further and allow you to test for a specific condition, bas ...
- [TypeScript] Typescript Interfaces vs Aliases Union & Intersection Types
TypeScript has 'interface' and 'type', so when to use which? interface hasName { firstName: string; ...
- [TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers
Using the optional “+” sign together with mapped type modifiers, we can create more explicit and rea ...
- Java中的Union Types和Intersection Types
前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联 ...
- Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.
代码如下: var query = from s in db.LoginUserServices join ss in db.Services on s.ServiceType equals ss.C ...
- [TypeScript] Restrict null and undefined via Non-Nullable-Types in TypeScript
This lesson introduces the --strictNullChecks compiler option and explains how non-nullable types di ...
随机推荐
- Java集合系列之HashMap
概要 第1部分 HashMap介绍 HashMap简介 HashMap 是一个散列表,它存储的内容是键值对(key-value)映射.HashMap 继承于AbstractMap,实现了Map.Clo ...
- 18. PROFILING
18. PROFILING PROFILING表提供语句分析信息. 其内容对应于SHOW PROFILE和SHOW PROFILES语句生成的信息(参见"SHOW PROFILE语法&quo ...
- (14) openssl x509(签署和自签署)
主要用于输出证书信息,也能够签署证书请求文件.自签署.转换证书格式等. openssl x509工具不会使用openssl配置文件中的设定,而是完全需要自行设定或者使用该伪命令的默认值,它就像是一个完 ...
- MariaDB数据库(一)
1.数据库简介 1.1 什么是数据库? 简单的说,数据库就是一个存放数据的仓库,这个仓库是按照一定的数据结构(数据结构是指数据的组织形式或数据之间的联系)来组织,存储的,我们可以通过数据库提供的多种方 ...
- React深入 - 手写redux api
简介: 手写实现redux基础api createStore( )和store相关方法 api回顾: createStore(reducer, [preloadedState], enhancer) ...
- solr中的schema.xml(managed-schema)文件解读
solr 7.2.1版本managed-schema文件示例 <uniqueKey>id</uniqueKey> 唯一键字段,solr对每一个文档都赋予一个唯一标识符字段,避免 ...
- ASP.NET MVC中如何在客户端进行必要的判断
背景:在开发网站时,往往需要对用户的输入进行合法性检查,如果验证工作都放在服务器端,势必将影响网页的响应速度,同时给用户不好的体验.本篇随笔即是使用JQuery在客户端进行必要的合法检测. JS代码如 ...
- ArrayList集合的遍历
ArrayLIstDemo3.java import java.util.ArrayList; public class ArrayListDemo3 { public static void mai ...
- mac 终端path配置出错,命令无法使用
mac 命令行中修改path的时候,不小心把path修改错了,而且还 source 了,然后发现只能使用 cd 命令,ls vi 命令都不能使用了. 解决办法,执行下面的语句 export PATH= ...
- 【05】Firebug动态执行JavaScript
Firebug动态执行JavaScript 您可以使用Firebug来编写并实时执行一个JavaScript. 这是为了测试,并确保该脚本工作正常,这是将JavaScript代码部署在生产环境前的好方 ...