问题描述
为什么下面的代码说Type 'string' is not assignable to type 'never'
?
但是,已编译的javascript效果很好
export enum MyStringsTest {
DEPART_IN_X_MINUTE='DEPART_IN_X_MINUTE',A_DRIVER_IS_ASKING_FOR='A_DRIVER_IS_ASKING_FOR',}
export interface Payloads {
[MyStringsTest.DEPART_IN_X_MINUTE]: number,[MyStringsTest.A_DRIVER_IS_ASKING_FOR]: string,}
type Cache = {
[K in keyof Payloads]?: (payload: Payloads[K]) => string
}
const cache: Cache = {}
function addToCache<K extends keyof Cache>(code: K,cb: (Cache[K])): void{
cache[code] = cb
}
addToCache(MyStringsTest.DEPART_IN_X_MINUTE,(data) => `Depart in ${data} minutes!`);
addToCache(MyStringsTest.A_DRIVER_IS_ASKING_FOR,(data) => `a driver is asking for ${data}`);
function getParsed<T extends keyof Cache>(stringCode: T,payload: Payloads[T]) {
const builder = cache[stringCode]
const ans = builder(payload as any) // <- error here
return ans;
}
getParsed(MyStringsTest.A_DRIVER_IS_ASKING_FOR,'a sandwitch')
getParsed(MyStringsTest.DEPART_IN_X_MINUTE,456)
// This prints "a driver is asking for a sandwitch"
// This prints "Depart in 456 minutes!"
跟踪Why is this code saying Type 'number' is not assignable to type 'never'
游乐场link
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)