基本上我想要实现的是合并这两个分支:
类响应Dto
export class ResponseDto<T = Record<string, any>> {
public readonly sucess = true;
constructor(
public data: T
) { }
}
类 可迭代响应Dto
export class IterableResponseDto<T = Record<string, any>[]> {
public readonly sucess = true;
constructor(
public data: T,
public paging: Paging
) { }
}
如您所见,当data
参数是数组时,您可以提供 certan 类型的paging
参数,否则只有data
是强制性的。
您可以使用条件类型来表示构造函数的 rest 参数元组的类型:
export class ResponseDto<T extends Record<string, any> | Array<Record<string, any>>> {
public readonly sucess = true;
public paging: Paging | undefined;
constructor(
public data: T,
...[paging]: (T extends Array<any> ? [Paging] : [])
) {
this.paging = paging;
}
}
上面,当且仅当T
的类型是数组时,将接受paging
参数。 在类的实现中,您将paging
属性设置为Paging | undefined
。 结果可能很难让类实现知道Paging
何时存在和不存在,因为编译器很难推理依赖于未指定泛型的条件类型。
但至少从调用方的角度来看,它应该按预期工作:
declare const paging: Paging;
const okayObject = new ResponseDto({ a: "hello" });
const badObject = new ResponseDto({ a: "hello" }, paging); // error!
// expected 1 arg, got 2
const okayArray = new ResponseDto([1, 2, 3], paging);
const badarray = new ResponseDto([1, 2, 3]); // error!
// expected 2 args, got 1
好的,希望有帮助;祝你好运!
操场链接到代码