typescript - 可以通过接收到的构造函数参数动态地计算类属性吗?
问题描述
基本上我想要实现的是合并这两个分类:
类 ResponseDto
export class ResponseDto<T = Record<string, any>> {
public readonly sucess = true;
constructor(
public data: T
) { }
}
类 IterableResponseDto
export class IterableResponseDto<T = Record<string, any>[]> {
public readonly sucess = true;
constructor(
public data: T,
public paging: Paging
) { }
}
正如你所看到的,当data
参数是一个数组时,你可以提供一个paging
特定类型的参数,否则只能data
是强制性的。
解决方案
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;
}
}
上面,当且仅当类型是数组时,paging
参数才会被接受。T
在类的实现中,您将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
好的,希望有帮助;祝你好运!
推荐阅读
- javascript - 如何进行倒计时编辑而不是一一发送消息?
- javascript - 我正在尝试使用 JS 从 xml 文件中删除一个元素
- json - 如何使用 Kusto 在字符串中解析嵌套的 JSON
- css - SVG图标继承文本颜色和大小
- docker - Docker 服务构建失败:拉取访问被拒绝,存储库不存在或可能需要“docker login”
- python - 在 pandas DF 中查找和替换重复值
- flutter - 音频文件无法在 IOS 模拟器中播放
- angular - 自动插入
*ngFor 中的值变化 - firebase - 将两个以上的帐户合并为一个
- python-3.x - 是否可以使用 python 在单点登录、两因素身份验证环境中访问 SharePoint 网站?