Reputation: 2977
I have a function that converts an integer to English words. I chain the array operations to convert the number in one go. The problem I have is in reduce() I have an array concat() which should always return string[] type, however typescript compiler complains that the type returned from reduce() is string[] | string. Therefore the map() after reduce() can't be called and tsc complains 'map does not exist on type string'.
inEnglish(n: number): string {
return n === 0? 'zero': n.toLocaleString().split(',')
.reverse()
.map((g, i) => Number(g)? [g, scales[i]]: g)
.reverse()
.reduce((g: string[], a) => g.concat(a), [])
.map(g => Number(g)? this.under1000(Number(g)): g)
.join('')
}
Since I know that concat() will always return type string[], how can I tell tsc that it will always be type string[] and not type string?
Upvotes: 1
Views: 848
Reputation: 249486
The solution would be to specify the result of reduce
explicitly:
var scales :string[] =[]
function inEnglish(n: number): string {
return n === 0? 'zero': n.toLocaleString().split(',')
.reverse()
.map((g, i) => Number(g)? [g, scales[i]]: g)
.reverse()
.reduce<string[]>((g, a) => g.concat(a), [''])
.map(g => Number(g)? this.under1000(Number(g)): g)
.join('')
}
Upvotes: 2