How to remove unnecessary casting with Ramda and Typescript

…衆ロ難τιáo~ 提交于 2021-01-29 08:57:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!