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

成都創(chuàng)新互聯(lián)公司為企業(yè)級(jí)客戶(hù)提高一站式互聯(lián)網(wǎng)+設(shè)計(jì)服務(wù),主要包括成都網(wǎng)站建設(shè)、成都做網(wǎng)站、成都App定制開(kāi)發(fā)、重慶小程序開(kāi)發(fā)公司、宣傳片制作、LOGO設(shè)計(jì)等,幫助客戶(hù)快速提升營(yíng)銷(xiāo)能力和企業(yè)形象,創(chuàng)新互聯(lián)各部門(mén)都有經(jīng)驗(yàn)豐富的經(jīng)驗(yàn),可以確保每一個(gè)作品的質(zhì)量和創(chuàng)作周期,同時(shí)每年都有很多新員工加入,為我們帶來(lái)大量新的創(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ù)來(lái)獲取其屬性的值。
const data = {
a: 3,
hello: 'max'
}
function get(o: object, name: string) {
return o[name]
}我們一開(kāi)始可能是這樣寫(xiě)的,但它有很多缺點(diǎn):
- 無(wú)法確認(rèn)返回類(lèi)型:這將失去 ts 的最大類(lèi)型檢查能力。
- 無(wú)法約束密鑰:可能會(huì)出現(xiàn)拼寫(xiě)錯(cuò)誤。
在這種情況下,可以使用 keyof 來(lái)增強(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
這些類(lèi)型內(nèi)置在 Typescript 中。
3.條件類(lèi)型?
它類(lèi)似于 ?: 運(yùn)算符,你可以使用它來(lái)擴(kuò)展一些基本類(lèi)型。
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 類(lèi)型表示從不出現(xiàn)的值的類(lèi)型。
結(jié)合 never 和條件類(lèi)型可以引入許多有趣和有用的類(lèi)型,例如 Omit
type Exclude= T extends U ? never : T;
// Equivalent to: type A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>
結(jié)合Exclude,我們可以介紹Omit的寫(xiě)作風(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è)取一定值的類(lèi)型,下面的例子展示了它們的用法
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
在此之前,我們先來(lái)看一個(gè)koa錯(cuò)誤處理流程, 這是集中錯(cuò)誤處理和識(shí)別代碼的過(guò)程。
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) 類(lèi)型上不存在屬性“code”。
在這種情況下,可以使用 as AxiosError 或 as any 來(lái)避免錯(cuò)誤,但是強(qiáng)制類(lèi)型轉(zhuǎn)換不夠友好!
if ((err as AxiosError).isAxiosError) {
code = `Axios-${(err as AxiosError).code}`
}在這種情況下,你可以使用 is 來(lái)確定值的類(lèi)型。
function isAxiosError (error: any): error is AxiosError {
return error.isAxiosError
}
if (isAxiosError(err)) {
code = `Axios-${err.code}`
}在 GraphQL 源代碼中,有很多這樣的用途來(lái)識(shí)別類(lèi)型。
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ū)別很小,比如下面兩種寫(xiě)法就差不多了。
interface A {
a: number;
b: number;
};
type B = {
a: number;
b: number;
}interface可以如下合并,而type只能使用 & 類(lèi)鏈接。
interface A {
a: number;
}
interface A {
b: number;
}
const a: A = {
a: 3,
b: 4
}
8. Record & Dictionary & Many
這些語(yǔ)法糖是從 lodash 的類(lèi)型源代碼中學(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)的問(wèn)題與 VS Code 提示的問(wèn)題不匹配。
在項(xiàng)目的右下角找到Typescript字樣,版本號(hào)顯示在右側(cè),你可以點(diǎn)擊它并選擇Use Workspace Version,表示它始終與項(xiàng)目所依賴(lài)的typescript版本相同。
或編輯 .vs-code/settings.json
{
"typescript.tsdk": "node_modules/typescript/lib"
}總之,TypeScript 增加了代碼的可讀性和可維護(hù)性,讓我們的開(kāi)發(fā)更加優(yōu)雅。
如果你覺(jué)得我今天的內(nèi)容對(duì)你有用的話(huà),請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將這篇文章分享給你的朋友,也許能夠幫助到他,最后,感謝你的閱讀,編程愉快!
網(wǎng)站題目:十個(gè)高級(jí)TypeScript開(kāi)發(fā)技巧
網(wǎng)頁(yè)網(wǎng)址:http://fisionsoft.com.cn/article/djjogip.html


咨詢(xún)
建站咨詢(xún)
