The Variant enum (enumerated list) lists all the possible variants. We have a handful of colours to choose from, if I need another colour for whatever reason, we can update this component, otherwise TypeScript will enforce that we can only use one of the Variants we have set up.
The IHorizontalPadding interface lets us describe the types of props the HorizontalPadding component can receive.
In this case we have the as prop which can let us change the type of element from a div to any other HTML element. The question mark means this field is not required, and string means it expects to receive some text. We can use it like this:
The children prop is a special property that React provides to make it easier to write JSX that looks similar to HTML.
Here is an example of using the HorizontalPadding component with a variant:
Next the HorizontalPadding component itself.
This is a React component that accepts the 3 props that we descripted in the IHorizontalPadding interface above. Both as and variant are provided a default value so that we don’t alway need to provide one (in this case the string “div” and the variant Variant.TRANSPARENT).
Finally we use the React.createElement function to create a new element based on the props that it has received. React.createElement accepts 3 parameters — the element to create, a props object, and a children component.
If I miss a required prop, or use the component incorrectly, TypeScript can let me know about that:
In this case it is telling us that the children prop is required.
Since we’ve gone to the trouble of listing all the different variants, TypeScript can see this and will display them inline — saving us time and ensuring we don’t make a typo.
Even if we did make a typo, TypeScript will pick that up and show us a useful error!
How cool is that, TypeScript can tell that ‘green’ is pretty close to ‘GREEN’ and offers us that as a suggestion!
By writing our code in TypeScript we’re forced to think more about how we author components, but it also saves us from a lot of potential errors.
We’re fully on board with TypeScript now, and are planning to use it on all new projects where possible. Once you get over the initial learning curve, the benefits are huge! You start out a little slower, but you spend less time debugging and are less likely to run into major bugs meaning happy clients and happy developers!