简体   繁体   中英

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

split function work on the string, Please look out this

toFixed function work on the Number, Please look out this

So, if you are converting res and res2 in proper format and then apply proper function. Might be you can catch your expected result.

I have done some changes to your code. (Converting res into the string and Converting res2 into a number). Please look out your changed code here and here

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