angular - Angular / TS:如何扩展接口
问题描述
我的问题很简单,虽然我找不到合适的解决方案。
我有以下界面:
export interface User {
id: number;
...
}
和方法
getCurrentUser(): Observable<User> {
return this.http.get<User>('url');
}
好的,现在,我想扩展一个用户对象,该getCurrentUser
方法返回附加方法。
我想到的第一件事是创建一个装饰器,像这样
export class UserDecorator implements User {
id: number;
constructor(private user: User) {}
someMethod() {
...
}
}
显然,我必须像这样使用它
.pipe(map((user: User) => new UserDecorator(user)))
我在这个解决方案中真正不喜欢的是
- 我必须将所有
User
属性复制/粘贴到UserDecorator
,将接口声明User
为类,以避免复制/粘贴,这也不是一个好的解决方案 - 将
User
对象设置为构造函数参数会导致以下问题- 我必须保持原样,并通过看起来不太好的
User
附加成员(例如)访问属性userDecorator.user.id
- 我必须在构造函数中手动将所有值从
User
to复制UserDecorator
。
- 我必须保持原样,并通过看起来不太好的
我的担心有意义吗?Angular 社区中是否有更好的解决方案,或者至少有一些传统的解决方案来解决这个问题?
谢谢你。
解决方案
使用继承和泛型,你可以做这样的事情。属性映射当然必须适应您的需求(手动或使用 Object.assign 或任何其他方式......)
class User {
private name = '';
constructor(data: any) {
this.name = data.name;
}
hi() {
return `Hi, I'm ${this.name}`;
}
}
class Employee extends User {
private job = '';
constructor(data: any) {
super(data);
this.job = data.job
}
work() {
return `Working as a ${this.job}`;
}
}
class MyDummyService {
private data = {
name: "John",
job: "bus driver"
}
getCurrentUser<T extends User>(u: new (data: any) => T): T {
return new u(this.data);
}
}
const dummyService = new MyDummyService()
const emp1 = dummyService.getCurrentUser(Employee) // will have the work method
console.log(emp1.hi(), emp1.work())
const emp2 = dummyService.getCurrentUser(User) // wont have the work method
console.log(emp2.hi() /*, emp2.work()*/)
推荐阅读
- wordpress - 这个 WordPress 网站使用什么文件下载方法?
- google-apps-script - 谷歌应用程序,加载项,“您无权调用 getUserProperties”
- linux - 仪表板不适用于 https - K8s 版本 - v1.19.6
- html - 在所有情况下,CSS网格自动最佳放置
- python - 如何在删除列中的匹配模式时忽略空值?
- list - 为什么数据会在列表中添加两次?
- arm - 如何在 Keil 上从头开始构建 Cortex M-7 项目?
- java - 无法验证连接池连接包装物理连接
- python - 在python中将用户输入数据插入sqlite3
- r - 减少 ggplot2 中误差线上限的大小