Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【2020TS】WHY using TypeScript开发??? #13

Open
bluezhan opened this issue May 23, 2020 · 0 comments
Open

【2020TS】WHY using TypeScript开发??? #13

bluezhan opened this issue May 23, 2020 · 0 comments

Comments

@bluezhan
Copy link
Member

  • 注释的妙用

我们可以通过/** */来注释TypeScript的类型,当我们在使用相关类型的时候就会有注释的提示,这个技巧在多人协作开发的时候十分有用

type returnType = ReturnType<typeof add>

  • 巧用元组

有时候我们可能需要批量的来获取参数,并且每一个参数的类型还不一样,我们可以声明一个元组如:

function query(...args:[string, number, boolean]){
  const d: string = args[0];
  const n: number = args[1];
  const b: boolean = args[2];
}
  • 巧用Omit
interface User {
    username: string
    id: number
    token: string
    avatar: string
    role: string
}
type UserWithoutToken = Omit<User, 'token'>
  • 运用Record

我们忘记写了一个汽车品牌,他会报错吗?
我们拼写属性名错误了,它会报错吗?
我们添加了一个非上述三个品牌的品牌进去,他会报错吗?
我们更改了其中一个品牌的名字,他会有报错提醒吗?
上述这种写法统统不会,这就需要Record的帮助。

type Car = 'Audi' | 'BMW' | 'MercedesBenz'
type CarList = Record<Car, {age: number}>

const cars: CarList = {
    Audi: { age: 119 },
    BMW: { age: 113 },
    MercedesBenz: { age: 133 },
}
  • 巧用类型约束

在 .jsx 文件里,泛型可能会被当做 jsx 标签

const toArray = <T>(element: T) => [element]; // Error in .jsx file.

加 extends 可破

const toArray = <T extends {}>(element: T) => [element]; // No errors.

  • 交叉类型
  • 联合类型
  • 类型别名

出自:Vue3.0之前你必须知道的TypeScript实战技巧

查看更多

@bluezhan bluezhan changed the title 【2020TS】什么使用TypeScript开发??? 【2020TS】WHY using TypeScript开发??? May 23, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant