0

I have the following code:

class Base<T> {}

class Test {
  prop: Base<any>;

  createProp<T>() {
    this.prop = new Base<T>();
  }
}

const test = new Test();

test.createProp<{ a: number }>();

test.prop // Base<any> expected Base<{ a: number }>

When I call createProp with the generic, I want it to be the new type of the prop property. Currently, after running this method, the type is still - Base<any>. There is a way to do it with TS?

1 Answer 1

1

prop is defined as Base<any> - it’ll never be a Base<T>, even if one is assigned to it.

In order to achieve this behaviour, you’ll have to make your class generic instead of just the method:

class Base<T> {}

class Test<T> {
  prop: Base<T>;

  createProp() {
    this.prop = new Base<T>();
  }
}

const test = new Test<{ a: number }>();

test.createProp();

test.prop

Alternatively, if you’re really against using a generic class, you could use a type assertion:

class Base<T> {}

class Test {
  prop: Base<any>;

  createProp<T>() {
    this.prop = new Base<T>();
  }
}

const test = new Test();

test.createProp<{ a: number }>();

test.prop as Base<{ a: number }>
// --- or ---
<Base<{ a: number }>> test.prop
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I know that I can do it like that, but I thought there be might a way to do it as I want.
Ah fair enough. You could cast the returned value, since you know its type from the generic on createProp. It’s a little messy but it would save you from creating a generic class if you’re trying to avoid it

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.