简体   繁体   中英

Typescript function return type based on argument

Is it possible to have a dynamic return type for the showTest function based on the definition of the TestType ?

If the argument is TestEnum.ONE , then the return type would be boolean , or in the case is TestEnum.TWO , then the return type would be string .

enum TestEnum {
  ONE= 'one',
  TWO= 'two'
}

type TestType = {
  [TestEnum.ONE]: boolean;
  [TestEnum.TWO]: number
}

const someObject = {
  [TestEnum.ONE]: true,
  [TestEnum.TWO]: 123
}

const showTest = (value: TestEnum) => {
  const result = someObject[value];
  if (typeof result === 'undefined') {
    throw new Error(`Unable to find ${value} in object`);
  }
  return result;
};

showTest(TestEnum.ONE) // return true and return type is boolean
showTest(TestEnum.TWO) // return 123 and return type is number

You can overload your function, so it would accept TestEnum and return different values depending on actual value of value .

enum TestEnum {
  ONE= 'one',
  TWO= 'two'
}

function showTest(value: TestEnum.ONE): boolean;
function showTest(value: TestEnum.TWO): string;
function showTest(value: TestEnum): boolean | string {
    if (value === TestEnum.ONE) return true;
    else if (value === TestEnum.TWO) return "not one";
    throw new Error('should never happen');
}

let shouldBeBoolean = showTest(TestEnum.ONE);
let shouldBeString = showTest(TestEnum.TWO);

Found a solution: TS Playground link here

enum TestEnum {
  ONE= 'one',
  TWO= 'two'
}

type TestType = {
  [TestEnum.ONE]: boolean;
  [TestEnum.TWO]: number
}

const someObject = {
  [TestEnum.ONE]: true,
  [TestEnum.TWO]: 123
}

const showTest = <K extends keyof TestType>(value: K): TestType[K] => {
  const result = someObject[value];
  if (typeof result === 'undefined') {
    throw new Error(`Unable to find ${value} in object`);
  }
  return result;
};

const boolValue = showTest(TestEnum.ONE) // return true and return type is boolean
const numberValue = showTest(TestEnum.TWO) // return 123 and return type is number

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