t-comm
Version:
专业、稳定、纯粹的工具库
50 lines (49 loc) • 1.46 kB
TypeScript
/**
* 将对象类型转换为元组类型(分散参数)
*
* @example
* ```ts
* interface MyParams {
* name: string;
* age?: number;
* city?: string;
* }
*
* // 手动指定顺序
* type MyArgs = ParamsToTuple<MyParams, ['name', 'age', 'city']>;
* // 结果: [string, number?, string?]
* ```
*/
export type ParamsToTuple<T, K extends readonly (keyof T)[]> = K extends readonly [infer First, ...infer Rest] ? First extends keyof T ? Rest extends readonly (keyof T)[] ? undefined extends T[First] ? [T[First]?, ...ParamsToTuple<T, Rest>] : [T[First], ...ParamsToTuple<T, Rest>] : [] : [] : [];
/**
* 创建支持对象参数和分散参数的函数重载类型
*
* @example
* ```ts
* interface ShowDialogParams {
* content: string;
* title?: string;
* }
*
* type ShowDialogFn = OverloadedFn<ShowDialogParams, ['content', 'title']>;
* // 等价于:
* // {
* // (params: ShowDialogParams): void;
* // (content: string, title?: string): void;
* // }
* ```
*/
export type OverloadedFn<T, K extends readonly (keyof T)[], R = void> = {
(params: T): R;
(...args: ParamsToTuple<T, K>): R;
};
/**
* 函数实现时的参数类型(联合类型)
*
* @example
* ```ts
* type ImplArgs = ImplementationArgs<ShowDialogParams, ['content', 'title']>;
* // 结果: [ShowDialogParams] | [string, string?]
* ```
*/
export type ImplementationArgs<T, K extends readonly (keyof T)[]> = [T] | ParamsToTuple<T, K>;