Search code examples
typescripttypescript-typingstypescript-genericsunion-types

TypeScript how to create a function with conditional return type?


I would like to write a function with a conditional return type. If the function gets passed a 'val1' as argument it returns a string type, if 'val2' returns number type and so on.

Simple example

playground: here

const store = {
  val1: 'string',
  val2: 1,
  val3: true
};

type INames = keyof typeof store; // "val1" | "val2" | "val3"
const getFromStore = (paramName: INames) => {
  return store[paramName];
};

const res = getFromStore('val1'); // return type is string | number | boolean instead of string
res.split(''); // error

Solution

  • const store = {
        val1: 'string',
        val2: 1,
        val3: true
    };
    
    const getFromStore = <K extends keyof typeof store>(paramName: K) => {
        return store[paramName];
    };
    
    const res = getFromStore('val1');
    res.split('');