0

I have two subClasses that will be extended to many classes. Now i will find a class with a specific type (in my case this is a property on the subClass).

After creating many instances i have a helper function that will return the first class with a match of needed type. So far everything works fine.

My Problem I do not get the correct ts-type when i return my class on my Helper funtion. I always get a typescript error but i have no idea how to solve that problem.

Is there anyone show me the right way to do it? Or is there some tutorial? (I found some tutorials but only withoud extends and no dynamic store array with many different types)

My example code on the typescript playground with the ts-error

1 Answer 1

1

I mentioned two things:

  1. You declared the array with type Building

    const buildingsStore: (Building)[] = [storehouse, barracks];

and then in the filter expecting building to have the property type:

return type === building.type;

This does obviously not work, because Building does not have type.

  1. I can't sadly explain what exactly goes on in TypeScript, but removing the return type of the function and type cast the result instead works (has somethign to do with Type Inference):

Working code here

EDIT

I updated my code regarding to the type property: here

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it works fine. I do not think this is the best solution but a big step to the next optimal solution.
You are welcome. Type Inference isn't that bad, btw.

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.