属性在 Typescript 中的自引用接口实现中不存在



我还是 Typescript 的新手,有人可以向我解释我在这里做错的地方吗?这是预期行为还是错误?

// interfaces/ValueObject.ts
export interface ValueObject {
  equals<T extends ValueObject> (valueObject: T): boolean;
  toString (): string;
}
// values/Age.ts
export class Age implements ValueObject {
  constructor (
    public readonly value: number,
  ) {}
  equals<Age> (anotherAge: Age): boolean {
    return anotherAge.value === this.value;
  }
  toString () {
    return `${this.value} year{this.value === 1 ? '' : 's'} old`;
  }
}

不知何故,我在编译时遇到了以下错误: Property 'value' does not exist on type 'Age'. 但我确实在构造函数中声明了属性值,我做错了什么吗?

当你写equals<Age> (anotherAge: Age): boolean时,<Age>引入了一个新的类型参数Age。这意味着参数定义中的Age不是您要定义的类Age,而是您在函数中引入的类型参数。

据我所知,您实际上希望接口采用与实现类相同类型的参数。要在 Typescript 中执行此操作,我们可以使用多态this

export interface ValueObject {
    equals(valueObject: this): boolean;
    toString(): string;
}
export class Age implements ValueObject {
    constructor(
        public readonly value: number,
    ) { }
    equals(anotherAge: Age): boolean {
        return anotherAge.value === this.value;
    }
    toString() {
        return `${this.value} year{this.value === 1 ? '' : 's'} old`;
    }
}

最新更新