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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 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(代码的主要内容,如果未能解决你的问题,请参考以下文章

typescript 怎么调用http的create接口

将 create-react-app 从 javascript 迁移到 typescript

typescript Observable.create

typescript Observable.create

create-react-app 可以与 TypeScript 一起使用吗

使用 typescript 在 create-react-app 中加载 sass