Typescript how do I dynamically use type of object property

Say I have some code like this:

type Action = {
    type: string;
    data: /* need help here */;
};

// data is a string here
const action1: Action = {
    type: 'foo',
    data: 'bar'
};

// data is an object here
const action2: Action = {
    type: 'complex',
    data: {
        first: 'John',
        last: 'Doe'
    }
};

// data is not defined here
const action3: Action = {
    type: 'undef'
};

// and so on, the point is data can be anything 

I want to have the type of data be whatever the type of data is on the object so that the previous code example will not give me any compiler errors. I don’t want to use any because I want to have my editor’s intellisense help with the type when I type. Is there a way in Typescript to do what I’m trying to do?

>Solution :

You can use a generic like this to represent that the type of data be potentially anything:

type Action<T> = {
    type: string;
    data?: T;
};

But when you define a variable, you would essentially have to duplicate the type, which is not useful. So that’s why we need a function to infer the generic for us:

function action<T = undefined>(a: Action<T>): Action<T> {
    return a;
}

Playground

Leave a Reply