#How do generics work for a destructured prop?

5 messages · Page 1 of 1 (latest)

wise coral
#

I have the following typescript code which doesn't seem to be producing any TS validation errors. But I'm not sure why it is working. So, the T that is defined on this line
const openModal = <T>({ data = null, modalId }: TOpenModal<T>) => ({
represents the type definition of the object which contains all the props. In TOpenModal I am using T to type data, but if T represents the whole object (not just data) why does it work?

type TOpenModal<T> = {
    data: T | null
    modalId: string
}

const openModal = <T>({ data = null, modalId }: TOpenModal<T>) => ({
    type: OPEN_MODAL,
    payload: {
        data,
        modalId,
    },
});
weak mason
#

@wise coral I'm not sure what you mean - for the input args T is the data prop and then you're using it as the data prop in the payload, too

#

The fact that those are the same name isn't really relevant, you could also do:

type TOpenModal<T> = {
    foo: T | null
    modalId: string
}

const openModal = <T>({ foo = null, modalId }: TOpenModal<T>) => ({
    type: OPEN_MODAL,
    payload: {
        bar: foo,
        modalId,
    },
});

and it wouldn't make a difference

wise coral
#

@weak mason Ok, so T represents only the data prop, not the entire object {data , modalId} ?

weak mason
#

Yes, because that's how you declared it:

type TOpenModal<T> = {
    data: T | null
    modalId: string
}