Home > Software engineering >  Record function argument as union type is not assignable to its union values
Record function argument as union type is not assignable to its union values

Time:01-21

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

TypeScript version: 4.3.2

Click here for the full code snippet on TS Playground

CodePudding user response:

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

  •  Tags:  
  • Related