V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
love
V2EX  ›  TypeScript

晕了,能看看这个 TypeScript 表达式有什么问题?

  •  
  •   love · 2019-06-26 18:48:46 +08:00 · 3568 次点击
    这是一个创建于 1757 天前的主题,其中的信息可能已经有所发展或是发生改变。
    let names: (string | string[])[] = ['a', ['b']]
    
    let aaa = names.reduce(result => {
        return result
    }, [] as string[])
    

    为什么最后 aaa 的类型是 string | string[] 呢?百思不得其解

    let names: (string | string[])[] = ['a', ['b']]
    
    let aaa = names.reduce(result => {
        return result
    }, [] as number[])
    

    用 number 后出来的是期望的 number[],这为什么二者会不一样呢?

    4 条回复    2019-07-27 13:34:32 +08:00
    love
        1
    love  
    OP
       2019-06-26 19:07:47 +08:00
    reduce 的定义:
    reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

    看上去没发现问题,心好累。。。
    love
        2
    love  
    OP
       2019-06-26 20:22:01 +08:00
    这样写可以绕过这个问题

    let aaa = names.reduce<string[]>(result => { return result }, [])
    agagega
        3
    agagega  
       2019-07-10 21:39:39 +08:00
    如果把 string | string[] 换成 string | number[] 测试会怎么样?
    Jex
        4
    Jex  
       2019-07-27 13:34:32 +08:00   ❤️ 1
    因为最为 Generic 的重载 reduce<U>的定义排在最后,你的 initialValue 因为和元素类型兼容,所以被前面的重载抢先匹配了:
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5322 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 01:21 · PVG 09:21 · LAX 18:21 · JFK 21:21
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.