2023-05-31

How to get the value type from a record in Typescript

I have a function which returns a record: ReturnType: Record<string, {...<SOME_BIG_TYPE>...}>, and another function that I would like to accept {...<SOME_BIG_TYPE>...} as an argument. How can I grab that type from the record?

I would like something like the following where ExtractedValueOf grabs that value I mentioned earlier.

const function = ({ bigObject }: { bigObject: ExtractedValueOf<ReturnType> }) => null;

I was thinking something like ReturnType<keyof ReturnType> but this does not work.

Edit: Added a basic example that illustrates my issue.

I have here a function that returns Record<string, SomeType>, which is used to call my other function, which takes an argument of SomeType. This is all typesafe and how I would expect it to work:

type SomeType = {
  field: string;
  another: string;
};

function sample(): Record<string, SomeType> {
  return {
    object: {
      field: "Hello",
      another: "World",
    },
  };
}

function myFunction() {
  return myOtherFunction(sample().object);
}

function myOtherFunction(sampleObject: SomeType) {
  // something in here
  return sampleObject;
}

The problem is, in the place I have defined myOtherFunction, I don't have access to SomeType directly. I have access to the return type from sample, but I can't figure out how to get SomeType out of Record<string, SomeType>



No comments:

Post a Comment