微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么这段代码说类型'string'不能分配给类型'never'

如何解决为什么这段代码说类型'string'不能分配给类型'never'

为什么下面的代码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 举报,一经查实,本站将立刻删除。