在使用了一段时间的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 实现一个 get 函数来获取其属性的值。

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

我们一开始可能是这样写的,但它有很多缺点:

  • 无法确认返回类型:这将失去 ts 的最大类型检查能力。
  • 无法约束密钥:可能会出现拼写错误。

在这种情况下,可以使用 keyof 来增强 get 函数的 type 功能,有兴趣的可以查看 _.get 的 type 标签及其实现。

function get<T extends object, K extends keyof T>(o: T, name: K): T[K] {
  return o[name]
}

2.必填&部分&选择

既然知道了keyof,就可以用它对属性做一些扩展,比如实现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">

这些类型内置在 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 类型表示从不出现的值的类型。

结合 never 和条件类型可以引入许多有趣和有用的类型,例如 Omit

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

结合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

在一个典型的服务器端项目中,我们经常需要将一些工具塞进上下文中,比如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 来避免错误,但是强制类型转换不够友好!

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有什么区别?你可以参考这里:

interface和type的区别很小,比如下面两种写法就差不多了。

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 的类型源代码中学习的,并且通常在工作场所中经常使用。

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 consts
const TODO_STATUS {
  TODO: 'TODO',
  DONE: 'DONE',
  DOING: 'DOING'
}

// Maintaining constants with const enum
const 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 编译时出现的问题与 VS Code 提示的问题不匹配。

在项目的右下角找到Typescript字样,版本号显示在右侧,你可以点击它并选择Use Workspace Version,表示它始终与项目所依赖的typescript版本相同。

或编辑 .vs-code/settings.json

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

总之,TypeScript增加了代码的可读性和可维护性,让我们的开发更加优雅。

原文地址:http://www.cnblogs.com/sexintercourse/p/16901785.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性