Home > Software design >  How to avoid whitespace when two variables are combined in TypeScript?
How to avoid whitespace when two variables are combined in TypeScript?

Time:08-19

I want two variables to be combined like ${type1}${type2} but spaces can be added between these types.

type Unit = '%' | 'px' | 'em' | 'vh' | 'vh' | 'rem' | 'ex'

type CssSizeType = `${number}${Unit}`

let marginSize : CssSizeType = '10      px' // not error

How do I prevent whitespace? and why doesn't it throw an error in this case?

CodePudding user response:

You could use the bigint type instead, which is likely more appropriate in this case.

type Unit = '%' | 'px' | 'em' | 'vh' | 'vh' | 'rem' | 'ex'
type CssSizeType = `${bigint}${Unit}`

let marginSize: CssSizeType = '10      px' // error
let marginSize2: CssSizeType = '10.5px' // error

If you want decimals, you could use:

type Unit = '%' | 'px' | 'em' | 'vh' | 'vh' | 'rem' | 'ex'
type CssSizeType = `${bigint}${Unit}` | `${bigint}.${bigint}${Unit}`

let marginSize: CssSizeType = '10      px' // error
let marginSize2: CssSizeType = '10.5px' // ok
  • Related