简体   繁体   中英

In TypeScript, how do I make a function's return type based on the return type of one of its arguments?

Is there some way I can have a function whose return type varies based on one of its arguments? For example:

interface Person {
  name: string;
  job: string;
}

interface Animal {
  name: string;
  deadly: boolean;
}

function getPerson(): Person {
  return {
    name: 'Bob',
    job: 'Manager',
  };
}

function getAnimal(): Animal {
  return {
    name: 'Spot',
    deadly: false,
  };
}

function create(generator: () => Person | Animal): ReturnType<typeof generator>[] {
  return []
}

const people = create(getPerson);

This is kind of close, except the type of people is (Person | Animal)[] . I need it to be Person[] - in other words, it can look at the getPerson argument and know that this function will return a Person . I realize, of course, I could rewrite the function so I can do this:

const people = create<Person>(getPerson);

But I'd rather have it infer this from the arguments somehow.

Figured it out! I just modified this part of the above code:

function create<M>(generator: () => M): M[] {
  return []
}

const people = create(getPerson);
const animals = create(getAnimal);

And that worked.

您已经弄清楚了,如果您想查找/了解更多信息,我只是想补充一下,该概念称为“泛型”。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM