Skip to content
Advertisement

Typescript: Generic function should not return union of all types

I managed to type the object currentProps so TS knows which properties it haves AND each property has its individual type (not an union of all possible types).

So far so good.

Then I have this generic function overrideForIndex which gets one of the possible properties, and should return its value. But it can’t be assigned, because its return-type is a union, and not the specific type.

Now I could just cast it as any and call it a day, but I am curious if there is a way to handle this properly without casting to any.

Here is the “simplified” example: (open in TS playground)

JavaScript

Advertisement

Answer

If you take a look at these lines, the types are acting how you are expecting them to.

JavaScript

However, when you use the forEach loop, you are effectively using the following, where n is the union type of the key names of MyProps:

JavaScript

Currently, TypeScript cannot untangle this. In addition, there is a great thread on why such a change could lead to unintentional consequences.

You should avoid using any in 99% of “use cases” for it as you are effectively turning TypeScript off. In most instances where you would use any, Record<KeyType, ValueType> is sufficient like so:

JavaScript

In that block, you effectively suppress the error without relying on turning TypeScript completely off. It will also throw an error if you did type propNames as Array<keyof MyTypeExtendingMyProps>.

Advertisement