1

I have some issue with generic property. And some solution for it. Regarding code below can you propose some other solution ?

 interface IConfig{
  property?: number;
}

interface IChildConfig extends IConfig{
  otherProperty?: number;
}

class Base<T extends Base<any, IConfig>, U extends IConfig>{

  protected _config: U | IConfig = {
    property: 10
  };

  public config(){
    return <U>this._config;
  }
}

class Child extends Base<Child, IChildConfig>{

  protected _config: IChildConfig = {
    property: 20,
    otherProperty: 10
  }
}

let a = new Child(),
  b = new Base();

a.config();
b.config();

In example I set _config property type to U | IConfig to avoid errors. If I'll remove "| Config" part compilator will raise errors. As I understand type U must be equal or extend IConfig interface.

1 Answer 1

2

If you set _config to type U then TypeScript can not possible now whether _config is of the correct type, because that depends on what U actually is. Also there is no such thing as property overloading in JavaScript.

The solution depends on what you really want to achieve, but this would work:

abstract class Base<T extends Base<any, IConfig>, U extends IConfig>{
  abstract config(): U;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Lodewijk. Reason why I'm in need of such structure that different children can have own config or base config property, so in some cases config can be extended and in other cases it can be base one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.