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

2019-06-26 18:48:46 +08:00
 love
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[],这为什么二者会不一样呢?

3578 次点击
所在节点    TypeScript
4 条回复
love
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
2019-06-26 20:22:01 +08:00
这样写可以绕过这个问题

let aaa = names.reduce<string[]>(result => { return result }, [])
agagega
2019-07-10 21:39:39 +08:00
如果把 string | string[] 换成 string | number[] 测试会怎么样?
Jex
2019-07-27 13:34:32 +08:00
因为最为 Generic 的重载 reduce<U>的定义排在最后,你的 initialValue 因为和元素类型兼容,所以被前面的重载抢先匹配了:
reduce(callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: T[]) => T, initialValue: T): T;

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/577759

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX