Home > Enterprise >  Typescript function return type based on argument
Typescript function return type based on argument

Time:11-26

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

CodePudding user response:

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);

CodePudding user response:

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
  • Related