Skip to content

How to overload operators in a generic class ? #1933

Closed
@xiong-pro

Description

@xiong-pro

Hi, I wrote a generic class, and try to overload the == operator.

class Foo<T> {
  name: string = '';

  // the value may be string or integer
  constructor(value: T) {
    if (isString<T>()) {
      this.name = value;
    }
    if (isInteger<T>()) {
      this.name = value.toString();
    }
  }

  @operator('==')
  protected eq<U>(right: Foo<U>): bool {
    return this.name == right.name;
  }
}

const f1 = new Foo<string>('abc')
const f2 = new Foo<u32>(123)

if (f1 == f2) {
  // do something ...
}

But it thrown an error.

ERROR AS212: Decorator '@operator' is not valid here.

   @operator('==')
   ~~~~~~~~~~~~~~~

I guess it's because the eq<U>, but don't know how to write the code. 😢

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions