日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
十個(gè)高級(jí)TypeScript開發(fā)技巧

在使用了一段時(shí)間的 Typescript 之后,我深深地感受到了 Typescript 在大中型項(xiàng)目中的必要性。 可以提前避免很多編譯期的bug,比如煩人的拼寫問題。 并且越來越多的包都在使用 TS,所以學(xué)習(xí)它勢(shì)在必行。

成都創(chuàng)新互聯(lián)公司為企業(yè)級(jí)客戶提高一站式互聯(lián)網(wǎng)+設(shè)計(jì)服務(wù),主要包括成都網(wǎng)站建設(shè)、成都做網(wǎng)站、成都App定制開發(fā)、重慶小程序開發(fā)公司、宣傳片制作、LOGO設(shè)計(jì)等,幫助客戶快速提升營(yíng)銷能力和企業(yè)形象,創(chuàng)新互聯(lián)各部門都有經(jīng)驗(yàn)豐富的經(jīng)驗(yàn),可以確保每一個(gè)作品的質(zhì)量和創(chuàng)作周期,同時(shí)每年都有很多新員工加入,為我們帶來大量新的創(chuàng)意。 

以下是我在工作中學(xué)到的一些更實(shí)用的Typescript技巧,今天把它整理了一下,分享給各位,希望對(duì)各位有幫助。

1.keyof

keyof 與 Object.keys 稍有相似,只是 keyof 采用了接口的鍵。

interface Point {
x: number;
y: number;
}
// type keys = "x" | "y"
type keys = keyof Point;

假設(shè)我們有一個(gè)如下所示的對(duì)象,我們需要使用 typescript 實(shí)現(xiàn)一個(gè) get 函數(shù)來獲取其屬性的值。

const data = {
a: 3,
hello: 'max'
}
function get(o: object, name: string) {
return o[name]
}

我們一開始可能是這樣寫的,但它有很多缺點(diǎn):

  • 無法確認(rèn)返回類型:這將失去 ts 的最大類型檢查能力。
  • 無法約束密鑰:可能會(huì)出現(xiàn)拼寫錯(cuò)誤。

在這種情況下,可以使用 keyof 來增強(qiáng) get 函數(shù)的 type 功能,有興趣的可以查看 _.get 的 type 標(biāo)簽及其實(shí)現(xiàn)。

function get(o: T, name: K): T[K] {
return o[name]
}

2.必填&部分&選擇

既然知道了keyof,就可以用它對(duì)屬性做一些擴(kuò)展,比如實(shí)現(xiàn)Partial和Pick,Pick一般用在_.pick中


type Partial = {
[P in keyof T]?: T[P];
};

type Required = {
[P in keyof T]-?: T[P];
};

type Pick = {
[P in K]: T[P];
};

interface User {
id: number;
age: number;
name: string;
};

// Equivalent to: type PartialUser = { id?: number; age?: number; name?: string; }
type PartialUser = Partial

// Equivalent to: type PickUser = { id: number; age: number; }
type PickUser = Pick

這些類型內(nèi)置在 Typescript 中。

3.條件類型?

它類似于 ?: 運(yùn)算符,你可以使用它來擴(kuò)展一些基本類型。

T extends U ? X : Y

type isTrue = T extends true ? true : false
// Equivalent to type t = false
type t = isTrue

// Equivalent to type t = false
type t1 = isTrue

4. never & Exclude & Omit

never 類型表示從不出現(xiàn)的值的類型。

結(jié)合 never 和條件類型可以引入許多有趣和有用的類型,例如 Omit

type Exclude = T extends U ? never : T;
// Equivalent to: type A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>

結(jié)合Exclude,我們可以介紹Omit的寫作風(fēng)格。

type Omit = Pick>;

interface User {
id: number;
age: number;
name: string;
};

// Equivalent to: type PickUser = { age: number; name: string; }
type OmitUser = Omit

5.typeof

顧名思義,typeof代表一個(gè)取一定值的類型,下面的例子展示了它們的用法

const a: number = 3
// Equivalent to: const b: number = 4
const b: typeof a = 4

在一個(gè)典型的服務(wù)器端項(xiàng)目中,我們經(jīng)常需要將一些工具塞進(jìn)上下文中,比如config、logger、db models、utils等,然后使用typeof。

import logger from './logger'
import utils from './utils'

interface Context extends KoaContect {
logger: typeof logger,
utils: typeof utils
}

app.use((ctx: Context) => {
ctx.logger.info('hello, world')

// will return an error because this method is not exposed in logger.ts, which minimizes spelling errors
ctx.loger.info('hello, world')
})

6.is

在此之前,我們先來看一個(gè)koa錯(cuò)誤處理流程, 這是集中錯(cuò)誤處理和識(shí)別代碼的過程。

app.use(async (ctx, next) => {
try {
await next();
} catch (err) {
let code = 'BAD_REQUEST'
if (err.isAxiosError) {
code = `Axios-${err.code}`
} else if (err instanceof Sequelize.BaseError) {

}
ctx.body = {
code
}
}
})

在 err.code 中,它將編譯錯(cuò)誤,即“Error”.ts(2339) 類型上不存在屬性“code”。

在這種情況下,可以使用 as AxiosError 或 as any 來避免錯(cuò)誤,但是強(qiáng)制類型轉(zhuǎn)換不夠友好!

if ((err as AxiosError).isAxiosError) {
code = `Axios-${(err as AxiosError).code}`
}

在這種情況下,你可以使用 is 來確定值的類型。

function isAxiosError (error: any): error is AxiosError {
return error.isAxiosError
}

if (isAxiosError(err)) {
code = `Axios-${err.code}`
}

在 GraphQL 源代碼中,有很多這樣的用途來識(shí)別類型。

export function isType(type: any): type is GraphQLType;

export function isScalarType(type: any): type is GraphQLScalarType;

export function isObjectType(type: any): type is GraphQLObjectType;

export function isInterfaceType(type: any): type is GraphQLInterfaceType;

7. interface & type

interface 和 type有什么區(qū)別? 你可以參考這里:https://stackoverflow.com/questions/37233735/interfaces-vs-types-in-typescript

interface和type的區(qū)別很小,比如下面兩種寫法就差不多了。

interface A {
a: number;
b: number;
};

type B = {
a: number;
b: number;
}

interface可以如下合并,而type只能使用 & 類鏈接。

interface A {
a: number;
}

interface A {
b: number;
}

const a: A = {
a: 3,
b: 4
}

8. Record & Dictionary & Many

這些語法糖是從 lodash 的類型源代碼中學(xué)習(xí)的,并且通常在工作場(chǎng)所中經(jīng)常使用。

type Record = {
[P in K]: T;
};

interface Dictionary {
[index: string]: T;
};

interface NumericDictionary {
[index: number]: T;
};

const data:Dictionary = {
a: 3,
b: 4
}

9. 用 const enum 維護(hù) const 表

Use objects to maintain constsconst TODO_STATUS {  TODO: 'TODO',  DONE: 'DONE',  DOING: 'DOING'}
// Maintaining constants with const enumconst enum TODO_STATUS { TODO = 'TODO', DONE = 'DONE', DOING = 'DOING'}
function todos (status: TODO_STATUS): Todo[];
todos(TODO_STATUS.TODO)

10. VS Code 技巧和 Typescript 命令

有時(shí)候用 VS Code,用 tsc 編譯時(shí)出現(xiàn)的問題與 VS Code 提示的問題不匹配。

在項(xiàng)目的右下角找到Typescript字樣,版本號(hào)顯示在右側(cè),你可以點(diǎn)擊它并選擇Use Workspace Version,表示它始終與項(xiàng)目所依賴的typescript版本相同。

或編輯 .vs-code/settings.json

{   
"typescript.tsdk": "node_modules/typescript/lib"
}

總之,TypeScript 增加了代碼的可讀性和可維護(hù)性,讓我們的開發(fā)更加優(yōu)雅。

如果你覺得我今天的內(nèi)容對(duì)你有用的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將這篇文章分享給你的朋友,也許能夠幫助到他,最后,感謝你的閱讀,編程愉快!


分享題目:十個(gè)高級(jí)TypeScript開發(fā)技巧
本文URL:http://www.5511xx.com/article/djjogip.html