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

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?

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

>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

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