是否可以通过接收的构造函数参数动态计算类属性?



基本上我想要实现的是合并这两个分支:

类响应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

好的,希望有帮助;祝你好运!

操场链接到代码

最新更新