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

以下是我在工作中學到的一些更實用的Typescript技巧,今天把它整理了一下,分享給各位,希望對各位有幫助。
1.keyof
keyof 與 Object.keys 稍有相似,只是 keyof 采用了接口的鍵。
interface Point {
x: number;
y: number;
}
// type keys = "x" | "y"
type keys = keyof Point;
假設我們有一個如下所示的對象,我們需要使用 typescript 實現(xiàn)一個 get 函數(shù)來獲取其屬性的值。
const data = {
a: 3,
hello: 'max'
}
function get(o: object, name: string) {
return o[name]
}
我們一開始可能是這樣寫的,但它有很多缺點:
- 無法確認返回類型:這將失去 ts 的最大類型檢查能力。
- 無法約束密鑰:可能會出現(xiàn)拼寫錯誤。
在這種情況下,可以使用 keyof 來增強 get 函數(shù)的 type 功能,有興趣的可以查看 _.get 的 type 標簽及其實現(xiàn)。
function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
return o[name]
}
2.必填&部分&選擇
既然知道了keyof,就可以用它對屬性做一些擴展,比如實現(xiàn)Partial和Pick,Pick一般用在_.pick中
type Partial<T> = {
[P in keyof T]?: T[P];
};
type Required<T> = {
[P in keyof T]-?: T[P];
};
type Pick<T, K extends keyof T> = {
[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<User>
// Equivalent to: type PickUser = { id: number; age: number; }
type PickUser = Pick<User, "id" | "age">
這些類型內(nèi)置在 Typescript 中。
3.條件類型?
它類似于 ?: 運算符,你可以使用它來擴展一些基本類型。
T extends U ? X : Y
type isTrue<T> = T extends true ? true : false
// Equivalent to type t = false
type t = isTrue<number>
// Equivalent to type t = false
type t1 = isTrue<false>
4. never & Exclude & Omit
never 類型表示從不出現(xiàn)的值的類型。
結(jié)合 never 和條件類型可以引入許多有趣和有用的類型,例如 Omit
type Exclude<T, U> = T extends U ? never : T;
// Equivalent to: type A = 'a'
type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>
結(jié)合Exclude,我們可以介紹Omit的寫作風格。
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
interface User {
id: number;
age: number;
name: string;
};
// Equivalent to: type PickUser = { age: number; name: string; }
type OmitUser = Omit<User, "id">
5.typeof
顧名思義,typeof代表一個取一定值的類型,下面的例子展示了它們的用法
const a: number = 3
// Equivalent to: const b: number = 4
const b: typeof a = 4
在一個典型的服務器端項目中,我們經(jīng)常需要將一些工具塞進上下文中,比如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
在此之前,我們先來看一個koa錯誤處理流程, 這是集中錯誤處理和識別代碼的過程。
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 中,它將編譯錯誤,即“Error”.ts(2339) 類型上不存在屬性“code”。
在這種情況下,可以使用 as AxiosError 或 as any 來避免錯誤,但是強制類型轉(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 源代碼中,有很多這樣的用途來識別類型。
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 的類型源代碼中學習的,并且通常在工作場所中經(jīng)常使用。
type Record<K extends keyof any, T> = {
[P in K]: T;
};
interface Dictionary<T> {
[index: string]: T;
};
interface NumericDictionary<T> {
[index: number]: T;
};
const data:Dictionary<number> = {
a: 3,
b: 4
}
9. 用 const enum 維護 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 命令
有時候用 VS Code,用 tsc 編譯時出現(xiàn)的問題與 VS Code 提示的問題不匹配。
在項目的右下角找到Typescript字樣,版本號顯示在右側(cè),你可以點擊它并選擇Use Workspace Version,表示它始終與項目所依賴的typescript版本相同。
或編輯 .vs-code/settings.json
{
"typescript.tsdk": "node_modules/typescript/lib"
}
總之,TypeScript 增加了代碼的可讀性和可維護性,讓我們的開發(fā)更加優(yōu)雅。
如果你覺得我今天的內(nèi)容對你有用的話,請記得點贊我,關(guān)注我,并將這篇文章分享給你的朋友,也許能夠幫助到他,最后,感謝你的閱讀,編程愉快!