问题
Consider
const darkPalette = [
'#255dbd',
'#2c6bd7',
'#5386e2',
'#7ea5e9',
'#49bbdb',
'#56d6f9',
'#89e2fa',
'#aaeafc',
'#00a690',
'#10bda4',
'#6ad8c8',
'#9de4da',
'#9dc53b',
'#bae050',
'#dcf0a3',
'#eaf6c8',
]
const transposePalette = compose(flatten, transpose, splitEvery(4))
const transposedDarkPalette = transposePalette(darkPalette)
When i receive the result of transposedDarkPalette the compiler complains:
Types of property 'color' are incompatible.
Type '{}[]' is not assignable to type 'string[]'.
Type '{}' is not assignable to type 'string'
I can fix this by doing
const transposedDarkPalette = (transposePalette(darkPalette) as unknown) as string[]
but it's kind of ugly and I'm wondering if there is a better way of doing this.
回答1:
The type inference of TS doesn't work well enough to bring the correct types through compose, as the commenters already stated.
One solution is so specify the generics of compose manually:
const transposePalette = compose<string[], unknown, unknown, string[]>(flatten, transpose, splitEvery(4))
The first generic is the input parameter, the last generic the output parameter. To keep the declaration short, the interim types are omitted.
来源:https://stackoverflow.com/questions/54363310/how-to-remove-unnecessary-casting-with-ramda-and-typescript