阅读antd源码过程中发现有些组件类型用tuple,不明白为啥要这样,全局搜索也没发现公用的地方,为啥不直接了当的写联合类型?
const tuple = <T extends string[]>(...args: T) => args;
const ButtonTypes = tuple('default', 'primary', 'ghost', 'dashed', 'link', 'text');
type ButtonType = typeof ButtonTypes[number];
// 'default' | 'primary' | 'ghost'| 'dashed' | 'link' | 'text'
为啥不直接写
type ButtonType = 'default' | 'primary' | 'ghost'| 'dashed' | 'link' | 'text'
没写是 React 还是 Vue 的,我就当作是 Vue 的。
这么写的好处是可以给
props
的validator
复用。那个tuple
实际就是个数组。比如可以:
这样当你瞎传一个 String 进去,控制台就会有警告。你要是单纯的用 TS 类型别名,它只是个标记,tsc 编译后这些玩意儿就擦除掉了。
当然了,我举的例子是为了更好地说明
props
是如何复用的,antd 里还不是这么直接裸写的validator
,而是用了一个 vue-types 库下封装好的oneOf
工具方法,但原理是一样的。React 版差不多,因为
oneOf
这个方法就是从 React 那学来的。