Skip to content

前置的不定量参数

Code

  • 如何类型标注?
ts
addImpl('boolean', 'string', 'number', (a, b, c) => {})

解析

ts
// 错误实现, 剩余必须在最后
declare function addImpl(...args: string[], fn: () => void): any;
// 参数合并在一起
declare function addImpl(...args: [
  ...string[],
  Function
]): any;
// 定义类型
type JSTypes = 'string' | 'number' | 'boolean' | 'symbol' | 'bigint' | 'undefined' | 'object' | 'function';
declare function addImpl(...args: [
  ...JSTypes[],
  Function
]): any;
// 2边有约束,修改成泛型
type JSTypeMap = {
  'string': string,
  'number': number,
  'boolean': boolean,
  'symbol': symbol,
  'bigint': bigint,
  'undefined': undefined,
  'object': object,
  'function': Function
}
type JSTypes = keyof JSTypeMap;
type ArgsType<T extends JSTypes[]> = {
  [I in keyof T]: JSTypeMap[T[I]]
}
declare function addImpl<T extends JSTypes[]>(...args: [
  ...T,
  (...args: ArgsType<T> => any
]): any;