Typescript | Putting it to Practice

2 months ago : 2 min read

After a few weeks of studying and brushing up on areas like Data Structures and Algorithms, I've recently finished a course on Typescript. After this, I started to revisit my favourite side project: a WCAG-compliant colour palette app. I've been creating a Colour Picker UI component and realised that I wanted to break it off from the central system.

const something = () => {
  //Do something 
}

Why?

Well, two reasons:

  1. I don't need the values from the colour picker to be cluttering my central app state.
  2. I can easily add in a hook to relay the value object from the component, complete with methods that include pre-formatted values that work with the utility I'm using: 'color-convert'. So, without further delay, here's my little colour picker:

Color Picker Screenshot

It's not entirely spit-polished just yet, as I've discovered styling range input can be a bit tricky. There's a slight bug within mobile browsers where the sliders' border is styled rather than the fill. However, I completely removed the component and was able to implement Typescript onto it. The UI is completely tied together, with the gradients adjusting visually, along with a hook that emits an object with hex, rgb, hsl, and lab colour codes.

Here's what I've learnt:

  • My typing hygiene transposing the component wasn't the best. My previous JSX wasn't the best at ensuring types, and the data passed; specifically my abstractions!
  • I completely forgot about the purpose of a *.d.ts file, so once I slapped my forehead for the oversight, VScode reopened all my files and told me to remove my explicit imports.
  • The new CRA --template typescript CLI worked wonders to get set up quickly, but I can't tell you how many times I was opening docs to find out what components were what types.

Most importantly, I found VScode was incredibly informative with errors. Suddenly my abstractions were too abstract and needed a rewrite, which made them more transparent. My state was interfering with handling invalid hex codes, and so I had to insert some middleware. All of this didn't run into errors in regular React + JSX; but given TSX, it made me double-check all my assumptions.