React Function Component in TypeScript Syntax breakdown
This is a draft!
Something I notice that a lot of people with less background in JavaScript or TypeScript trip over is this:
export const MyComponent = <T,>(props: {
someArg: string,
someList: T[]
}) => (
<>
{/* some react code */}
</>
)
Having written JS/TS+React as long as I have, I didn’t see an issue. So I was rather surprised when an experienced developer, but inexperienced in JS/TS+React, reached out to me about this:
“What the actual fuck is this?” - “What exactly?” - “What does any of this do? Where do I put what? What’s going on here?”.
And then I laughed as I saw how weird all those <,>({:})=> must be for someone who has to touch this type of code only on occasion.
This is almost rust-level of symbolery.
I then started to ask during pairings, when it became obvious that someone was merely memorising or guessing the syntax, and getting it wrong, wether they knew what all this meant.
So let’s break this down, so I have something I can link to in the future:
Anonymous functions
const addOne = (value: number) => value + 1
() => "return value" is an expression for a anonymous function; a special kind.
Most of the time, these can be considered equivalent:
function addOne(value: number) { return value + 1 }
const addOne = function(value: number) { return value + 1 }
const addOne = (value: number) => { return value + 1 }
const addOne = (value: number) => value + 1
The difference between () => and function(){} is important and is about how JS handles this, which you might have seen in the context of a class to refer to its instance.
But in JS this is not exclusive to classes, can be a real footgun and thus it’s largely avoid outside of classes.
Destructuring
const book = {
title: "Lord of the Rings"
}
const { title } = book
Title is now a reference to the string Lord of the Rings.
Strings are immutable in JS, so it is often be thought of “title has the value of book.title”.
But those are different.
It’s rather a constant pointer to where book.title is pointing to at the time of evaluation.
const book = {
title: "Lord of the Rings",
author: {
name: "Tolkien"
}
}
const {title, author} = book
book.title = "foobar"
// title will still be "Lord of the Rings"