码迷,mamicode.com
首页 > 移动开发 > 详细

[TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers

时间:2019-01-17 21:20:45      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:creat   col   nbsp   for   pes   div   ase   can   exist   

Using the optional “+” sign together with mapped type modifiers, we can create more explicit and readable type declarations. We can also use the “-” (minus) sign to remove optional declarations from properties.

 

For example, we have an interface:

interface IPet { 
    name: string;
    age: number;
    favoritePark?: string
}

There is two required props and one favoriatePark as optional prop.

 

From TypeScirpt 2.8, we are able to gereate a new interface based on existing one, and add or remove props:

For example we want to remove all the optional props, we can use ‘-‘:

interface IPetRequired {
  [K in keyof IPET]-?: IPet[K]
}

‘-‘: remove

‘?‘: optional

‘-?‘: remove optional

 

We can also use ‘+‘ to indicate what we have added:

type ReadonlyPet = {
    +readonly [K in keyof IPet]?: IPet[K]
}

Here we added readonly type.

[TypeScript] Create Explicit and Readable Type Declarations with TypeScript mapped Type Modifiers

标签:creat   col   nbsp   for   pes   div   ase   can   exist   

原文地址:https://www.cnblogs.com/Answer1215/p/10284223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!