styled-components / polished

A lightweight toolset for writing styles in JavaScript ✨
https://polished.js.org/
MIT License
7.64k stars 209 forks source link

`getValueAndUnit` return type is misleading #589

Closed mrjackdavis closed 3 years ago

mrjackdavis commented 3 years ago

Mixin/Helper/Shorthand Usage

getValueAndUnit(
 // ...
)

What You Are Seeing

Response type of getValueAndUnit is any

What You Expected To See

Documentation suggests it resolves a tuple

// Styles as object usage
const styles = {
  '--dimension': getValueAndUnit('100px')[0],
  '--unit': getValueAndUnit('100px')[1],
}

I was going to propose a new change, but I found the return of the function quite unstable (e.g. it returned [ initialValue, undefined ] if there's no match.

Below is an API which I find preferable, but it'd be considered a breaking change. So I've made an issue for advice from the maintainers on how to progress. (And I wrote it in TS, not sure how it would look in flow)

See the example in action

const cssRegex = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/

function getValueAndUnit(value: string): [number, string | undefined] | undefined{
  const matchedValue = value.match(cssRegex);
  if (matchedValue){
    const nonEmptyUnitOrUndefined = matchedValue[2].length > 0 ? matchedValue[2] : undefined;
    return [parseFloat(matchedValue[1]), nonEmptyUnitOrUndefined];
  }
  return undefined;
}

console.log([
  getValueAndUnit("100px"),
  getValueAndUnit("100"),
  getValueAndUnit("px"),
])

/*
[
  [100, "px"],
  [100, undefined],
  undefined
]
*/

Reproduction

const output = getValueAndUnit("100px");

// output is typed `any`
bhough commented 3 years ago

@mrjackdavis Thank you for raising this. This is unlikely to be something we address in v4 of polished. We have a fair amount of type issues that we hope to address in v5 as part of our TS rewrite. Due to some quirks of flow and how we convert those to TS programmatically, we can't address these cases in the way we'd like. We will add this to our list of considerations for v5.