ridermansb
ridermansb

Reputation: 11059

Record with union type in typescript it's not working

What I'm doing wrong?

I need type that accept an object with properties and functions callback.. like this one

type EventCallback = () => void
type EventsType =
    | 'beforeshow'
    | 'show'
    | 'shown'
    | 'beforehide'
    | 'hidden'
    | 'hide';

type UIkitModalEvents = Record<EventsType, EventCallback>;

const event2: UIkitModalEvents = { /// ERROR ON event2 variable
    hidden: () => {
        console.log('s');
    },
};
console.log(event2);

Type '{ hidden: () => void; }' is missing the following properties from type 'Record<EventsType, EventCallback>': beforeshow, show, shown, beforehide, hide(2739)

You can check on playground

Upvotes: 2

Views: 692

Answers (1)

Lesiak
Lesiak

Reputation: 25986

With your current code you need to provide a callback for each event type. To make your code more flexible and accept an object with any subset of event types, you can use Partial

const event2: Partial<UIkitModalEvents>

Upvotes: 1

Related Questions