1

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?

4
  • 1
    So, you want something like this? Commented Sep 23, 2022 at 15:22
  • @caTS That's extremely close to what I want. I'm assuming the function used for initializing the objects is necessary? Commented Sep 23, 2022 at 15:25
  • 1
    Yes, otherwise you will have to use const act: Action<...> = { data: ... };, essentially duping the type you want. The function is there to infer the type for you. Commented Sep 23, 2022 at 15:27
  • Thanks! I'd mark your comment as the answer if I could. Commented Sep 23, 2022 at 15:28

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.