Issue
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?
Solution
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 {
//...
}
Answered By - Alex Wayne
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.