threepointone/glamor

Using css to generate a string for a className doesn't have the right TypeScript type

Closed this issue · 3 comments

If I use css(...) to generate a string to use as a className, I need to cast it as a string, otherwise I get this TypeScript error:

Argument of type 'StyleAttribute' is not assignable to parameter of type 'string'.
otbe commented

Whats your use case? Something like:

<div className={css(...)}/> {/* fails */}
<div className={css(...).toString()}/> {/* works */}
<div className={css(...) + ' my-class'}/> {/* works */}

I think its legit that TS forces you to call toString() or to kick off a type conversion by concatenating.

See this playground example.

I wonder what we can do there :/

css() returns an object that looks like

{
  'data-css-<hash>': '',
  toString: () => 'css-<hash>'
}

With this object you can spread it onto an element and it will get a data- property, which is targeted by the compiled styles.

To get the className you have to coerce to a string. Since React allows objects in props, it seems legitimate that you have to do the coercion by calling toString() or implicitly via a template string `${css(...)}` to not get typescript errors.

coercing to string sounds like a good solution to me :) I wasn't sure what the type expectation should be, as the examples show it being used without coercion.