Handle CSS units system in a type-safe way using TypeScript

Karibash
2 min readAug 7, 2021

--

I’ve created a library that can handle the CSS unit system in a type-safe way with TypeScript, and convert units from one to another.
If you find it useful, I’d appreciate it if you’d give it a star in the repository.

Install

npm install @karibash/pixel-units

Usage

Handle the CSS unit system in a type-safe

import { Unit } from '@karibash/pixel-units';const pixel: Unit<'px'> = '16px';
const rem: Unit<'rem'> = '1rem';
console.log({ pixel, rem });
// -> {pixel: "16px", rem: "1rem"}

Convert CSS unit systems to each other

import { Unit, convertUnits } from '@karibash/pixel-units';const pixel: Unit<'px'> = '32px';
const rem = convertUnits(pixel, 'rem');
console.log(rem);
// -> "2rem"

Extract numeric values and units from the unit system

import { Unit, splitUnitValue } from '@karibash/pixel-units';const pixel: Unit<'px'> = '32px';
const { value, unitSuffix } = splitUnitValue(pixel);
console.log({ value, unitSuffix });
// -> {value: 32, unitSuffix: "px"}

Example of use in React

import React from 'react';
import { Unit } from '@karibash/pixel-units';
type Props = {
padding: Unit<'rem'>
}
const Wrapper: React: FC<Props> = ({
children,
padding,
}) => {
return (
<div css={{ padding: `${padding}` }}>
{children}
</div>
);
};
export default Wrapper;

As an example, we will define a Wrapper component that can dynamically switch between the following paddings.

The padding property can be restricted so that it can only accept rem units.
If a value other than rem unit is specified, a compile error will occur.

import React from 'react';
import { Unit } from '@karibash/pixel-units';
import Wrapper from 'components/wrapper';
const Page: React:FC = () => {
return (
<>
<Wrapper padding={'2rem'}>
rem padding only
</Wrapper>
<Wrapper padding={'16px'}>
compile error
</Wrapper>
</>
);
};
export default Page;

--

--

No responses yet