antd源码中类型为啥要用tuple,直接写不明显么?

阅读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'
阅读 1.8k
1 个回答

没写是 React 还是 Vue 的,我就当作是 Vue 的。

这么写的好处是可以给 propsvalidator 复用。那个 tuple 实际就是个数组。

比如可以:

props: {
   type: {
      type: String,
      validator: (value) => ButtonTypes.includes(value) // 数组才有 includes 方法
   }
}

这样当你瞎传一个 String 进去,控制台就会有警告。你要是单纯的用 TS 类型别名,它只是个标记,tsc 编译后这些玩意儿就擦除掉了。

当然了,我举的例子是为了更好地说明 props 是如何复用的,antd 里还不是这么直接裸写的 validator,而是用了一个 vue-types 库下封装好的 oneOf 工具方法,但原理是一样的。

React 版差不多,因为 oneOf 这个方法就是从 React 那学来的。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题