Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Record function argument as union type is not assignable to its union values

The goal is to declare a Record type definition for a mapper in order to restrict the keys and function values.
The arguments of those functions have different behaviors, thus are defined using a union type.

PushNotificationPayloadVideoComment is part of PushNotificationPayload union type, but the TS compiler detects that it’s not assignable to its union

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TypeScript version: 4.3.2

Click here for the full code snippet on TS Playground

>Solution :

Using unknown means the function assigned should be capable to handle any parameter type, and you are using functions that can only handle a specific type.

You could use a custom mapped type to map each callback to the appropriate parameter type:

type Mapper = {
  [P in PushNotificationPayload as P['category']]?: (payload: P) => void
}

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading