V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
love

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

  •  
  •   love · Jun 26, 2019 · 4195 views
    This topic created in 2511 days ago, the information mentioned may be changed or developed.
    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 replies    2019-07-27 13:34:32 +08:00
    love
        1
    love  
    OP
       Jun 26, 2019
    reduce 的定义:
    reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

    看上去没发现问题,心好累。。。
    love
        2
    love  
    OP
       Jun 26, 2019
    这样写可以绕过这个问题

    let aaa = names.reduce<string[]>(result => { return result }, [])
    agagega
        3
    agagega  
       Jul 10, 2019
    如果把 string | string[] 换成 string | number[] 测试会怎么样?
    Jex
        4
    Jex  
       Jul 27, 2019   ❤️ 1
    因为最为 Generic 的重载 reduce<U>的定义排在最后,你的 initialValue 因为和元素类型兼容,所以被前面的重载抢先匹配了:
    reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3333 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 12:34 · PVG 20:34 · LAX 05:34 · JFK 08:34
    ♥ Do have faith in what you're doing.