Home > other >  TypeScript: Change return type based on another type from an object
TypeScript: Change return type based on another type from an object

Time:01-29

So what I am trying to do is demonstrated by the following working code:

type Records = {
  user: {
    id: string;
    name: string;
    age: number;
  },
  device: {
    id: string;
    brand: string;
    manufacturer: string;
  }
}

function getRecord (record: keyof Records, id: number) {
  return {} as Records['user']; // this is bad, should be a variable instead of hard coded.
}

const record = getRecord1('user', 123);
//    ^ becomes a user type

However, as you can see on the getRecord function, I have to hard-code the return as Records['user'], what I want is for it to be a variable such that the return type becomes the type of a property inside of Records, I'm trying to achieve this flexibility by deriving the return type of the function from its arguments, but I can't seem to find a way to do that, as demonstrated by the non-working code below.

type Records = {
  user: {
    id: string;
    name: string;
    age: number;
  },
  device: {
    id: string;
    brand: string;
    manufacturer: string;
  }
}

function getRecord (record: keyof Records, id: number) {
  return {} as Records[typeof record]; // unfortunately I can't do Records[record]
}

const record = getRecord('user', 123);
//     ^ Should become Records.user type, but it doesn't

CodePudding user response:

You need to convert this function to a generic one:

function getRecord<T extends keyof Records>(record: T, id: number): Records[T] {
  return {} as Records[T];
}

const record = getRecord('user', 123);

See in the playground

  • Related