首页 > 解决方案 > 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)))

我在这个解决方案中真正不喜欢的是

我的担心有意义吗?Angular 社区中是否有更好的解决方案,或者至少有一些传统的解决方案来解决这个问题?

谢谢你。

标签: angulartypescript

解决方案


使用继承和泛型,你可以做这样的事情。属性映射当然必须适应您的需求(手动或使用 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()*/)

推荐阅读