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. k8s集群部署之环境介绍与etcd数据库集群部署

    角色 IP 组件 配置 master-1 192.168.10.11 kube-apiserver kube-controller-manager kube-scheduler etcd 2c 2g ...

  2. Format a Hard Drive in Csharp

    Article Author(s): Audric Thevenet All Rights Reserved. Here's how to format hard drives, floppies, ...

  3. Java集合(六)--ArrayList、LinkedList和Vector对比

    在前两篇博客,学习了ArrayList和LinkedList的源码,地址在这: Java集合(五)--LinkedList源码解读 Java集合(四)--基于JDK1.8的ArrayList源码解读 ...

  4. Java 编程下 Eclipse/myeclipse 如何设置单行代码显示的最大宽度

    http://www.cnblogs.com/sunzn/archive/2013/03/30/2990191.html 或 http://zhidao.baidu.com/link?url=67uy ...

  5. hdu 6441 Find Integer(费马大定理+勾股数)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6441(本题来源于2018年中国大学生程序设计竞赛网络选拔赛) 题意:输入n和a,求满足等式a^n+b^ ...

  6. [CF] 948A Protect Sheep

    A. Protect Sheep time limit per test1 second memory limit per test256 megabytes inputstandard input ...

  7. 如何用纯 CSS 创作一种有削铁如泥感觉的菜单导航特效

    效果预览 在线演示 按下右侧的"点击预览"按钮可以在当前页面预览,点击链接可以全屏预览. https://codepen.io/comehope/pen/XqYroe 可交互视频教 ...

  8. POJ 3259 Wormholes(负权环路)

    题意: 农夫约翰农场里发现了很多虫洞,他是个超级冒险迷,想利用虫洞回到过去,看再回来的时候能不能看到没有离开之前的自己,农场里有N块地,M条路连接着两块地,W个虫洞,连接两块地的路是双向的,而虫洞是单 ...

  9. .NET Core使用log4Net记录日志

    1.引入Nuget包 log4net 2.添加log4Net配置文件 <?xml version="1.0" encoding="utf-8" ?> ...

  10. 【】关闭QQ右下角各种弹框

    []关闭QQ右下角弹框   一:     二:   超级会员设置过滤(屏蔽)广告后可以过滤哪些广告? 1.可以过滤QQ客户端好友聊天对话框右侧出现的Flash广告.左下角的文案广告: 如图: 2.可以 ...