Typescript 小技巧

2021/5/10 18:25:21

本文主要是介绍Typescript 小技巧,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Typescript 小技巧

总结下工作中用到的 typescript 的一些小技巧。

反向引用类型的属性的类型

假如我们有这样一个类型:

interface ButtonProps {
  theme: 'default' | 'primary' | 'async';
}

如何使用 ButtonProps 中定义的 theme 的类型?

type Theme = ButtonProps['theme']; // 'default' | 'primary' | 'async'

获取数组类型值的类型

假如有以下类型:

interface Car {
  model: { value: string; year: number }[];
  type: 1 | 2;
}

如何使用 Car 类型中的 model 类型呢?

type CarModel = Car['model'][number]; // {value: string, year: number};

这样可以让我们减少类型的命名,对英语水平稍弱的同学很有用。



这篇关于Typescript 小技巧的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程