Home > front end >  Define what return will be depending on param passed
Define what return will be depending on param passed

Time:07-02

I know all the possible values a param of a function can be. And if the param is a certain key, I know what the value will be. I am typing up the redis.get function for those of you that are familiar with redis. It's a key-value store.

type IA = 'a'
type IAData = string;

type IB = 'b'
type IBData = number;

type IRedisGet =
  | ((key: IA) => IAData)
  | ((key: IB) => IBData)

export const redistGet: IRedisGet = (key) => {
  if (key === 'a') {
    return 'a';
  } else if (key === 'b') {
    return 12;
  } else {
    throw new Error('invalid key');
  }
}

However this gives me the error:

Type '(key: any) => "a" | 12' is not assignable to type 'IRedisGet'.
  Type '(key: any) => "a" | 12' is not assignable to type '(key: "a") => string'.
    Type 'string | number' is not assignable to type 'string'.
      Type 'number' is not assignable to type 'string'.ts(2322

Does anyone know how to do this in Typescript?

CodePudding user response:

Function overloads are typically how to handle this.

function redisGet(key: IA): IAData
function redisGet(key: IB): IBData
function redisGet(key: IA | IB): IAData | IBData {
  //...
}

See playground

  • Related