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的更多相关文章

  1. [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 ...

  2. [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 ...

  3. [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 ...

  4. [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 ...

  5. [TypeScript] Typescript Interfaces vs Aliases Union & Intersection Types

    TypeScript has 'interface' and 'type', so when to use which? interface hasName { firstName: string; ...

  6. [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 ...

  7. Java中的Union Types和Intersection Types

    前言 Union Type和Intersection Type都是将多个类型结合起来的一个等价的"类型",它们并非是实际存在的类型. Union Type Union type(联 ...

  8. 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 ...

  9. [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 ...

随机推荐

  1. Windows 7桌面显示图标窗口句柄的获取

    在windows XP时代,我们获取桌面图标窗口的句柄往往用一下语句: HWND hwndParent = ::FindWindow( "Progman", "Progr ...

  2. 搜索 || DFS || UOJ 146 信息传递

    DFS+回溯 找最小环 每个人知道自己的生日,每次把自己知道的生日告诉固定的一个人,问最少多少次之后能从别人口中听到自己的生日 找一个最小环 #include <iostream> #in ...

  3. [BZOJ3211]:花神游历各国(小清新线段树)

    题目传送门 题目描述: 花神喜欢步行游历各国,顺便虐爆各地竞赛.花神有一条游览路线,它是线型的,也就是说,所有游历国家呈一条线的形状排列,花神对每个国家都有一个喜欢程度(当然花神并不一定喜欢所有国家) ...

  4. Sqlserver查询结果集插入新表

    数据库“Test” 数据库“Test2” 表 “fromTable” 表 “toTable” 表 “newTable” 字段 “name”,“age”,“gender” 原因:公司有2个数据库,一个是 ...

  5. Shell读取一个表达式并计算其结果

    #!/bin/bash # 读取一个算数表达式并计算出结果 # 如果输入 # 5+50*3/20 + (19*2)/7 # 则结果为 # 17.929 read x printf "%.3f ...

  6. LNOI2019划水记

    十二省联考命题组温馨提醒您: 数据千万条,清空第一条. 多测不清空,爆零两行泪. NOIp2018差点退役的游记 $Flag$拔了. $LNOI2019$划水记: $Day0$: 早上八点起床,一直颓 ...

  7. 嵩天老师的零基础Python笔记:https://www.bilibili.com/video/av13570243/?from=search&seid=15873837810484552531 中的15-23讲

    #coding=gbk#嵩天老师的零基础Python笔记:https://www.bilibili.com/video/av13570243/?from=search&seid=1587383 ...

  8. npm 的作用

    接触 npm 也有一个多月的时间了,一直只是将他作为当着 webstorm + node.js 环境中的一个插件来用(甚至说把她当着命令来用).毕竟大部分的时间,他是输入的命令行中的一部分(别笑,小新 ...

  9. OpenSSH高级功能之端口转发(Port Forwarding)

    在RedHat提供的系统管理员指南中提到OpenSSH不止是一个安全shell,它还具有X11转发(X11 Forwarding)和端口转发(Port Forwarding)的功能.X11功能一般用于 ...

  10. NGINX模块(二)

    [Nginx标准HTTP模块] 一.HTTP核心模块 指令1:alias 语法:alias file-path|directory-path; 默认值:no 使用字段:location 说明:这个指令 ...