1

I have a global type as below:

declare global {
    type ResponseData = {
        opcode: number;
        message: string;
        data?: <WILL-CHANGE-ON-EACH-CASE>;
    };
}

I want to put a custom type on data field in each specific returns. For example:

interface AppInformation {
    NAME: string;
    VERSION: string;
}

// What should I put on a return type???
export const getAppInfo = (): {...ResponseData, data: AppInformation } => {
    return apiResponse.success(200, CONFIG.APP);
};

What should I put on a return type of getAppInfo? I leave something to get the idea of what I'm looking for.

Thanks beforehand,

2
  • 1
    Presumably you want ResponseData to be generic like this (web IDE link), but the example code here isn't a minimal reproducible example so I'm not sure. Please consider modifying your example code so that it demonstrates what you're doing when dropped into an IDE without dependencies on undeclared values or types. Commented Sep 2, 2021 at 14:32
  • @jcalz that was exactly what I was expecting! Thanks, solved! Commented Sep 2, 2021 at 14:42

1 Answer 1

2

You want ResponseData to be a generic type, with a type parameter (such as) T that represents the type of the data property:

type ResponseData<T> = {
  opcode: number;
  message: string;
  data?: T
};

Then you can specify T when you want, to "plug in" a specific type like AppInformation:

interface AppInformation {
  NAME: string;
  VERSION: string;
}

const getAppInfo = (): ResponseData<AppInformation> => {
  return {
    opcode: 1, message: "msg", data: {
      NAME: "name", VERSION: "ver"
    }
  }
};

And the compiler will understand that the data (if present) will be of type AppInformation:

console.log(getAppInfo().data?.NAME.toUpperCase())

Playground link to code

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.