我知道函数参数的所有可能值。如果参数是某个键,我就知道它的值是什么。我把redis.get
函数输入给熟悉redis的人。这是一个键值存储
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');
}
}
然而这给了我错误:
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
有人知道如何在Typescript中做到这一点吗?
函数重载是典型的处理方法。
function redisGet(key: IA): IAData
function redisGet(key: IB): IBData
function redisGet(key: IA | IB): IAData | IBData {
//...
}
看到操场