DEV Community

Kaemon Lovendahl
Kaemon Lovendahl

Posted on

Using TypeScript with React, the Syntax

This is part 2 of my TypeScript series to help myself and others better understand what TypeScript is and how to use it with React.

Typing

JavaScript is a dynamically typed language. Meaning that you can declare a variable of one type of value, say a string, then reassign the same variable to another value like a number without issue.

let color= "blue"
color= 42 // This is fine
Enter fullscreen mode Exit fullscreen mode

TypeScript allows us to write JavaScript as a Staticly Typed language. We get to declare a type that goes along with any variable, parameter, or object.

let color: string = "blue"
color = 42 // This will not compile
Enter fullscreen mode Exit fullscreen mode

JavaScript Syntax

TypeScript supports JavaScript out of the box because it's a superset of JavaScript, meaning that it compiles to JavaScript. Declaring types is super easy and doesn't require as much effort as you'd think. Here's an example of the general syntax used.

Variables const userName: string = 'Kevin'

Parameters const addTwo = (value: number) => value + 2

and expected return values for functions.

const sayHello = (): string => "Hello"

You can use any JavaScript primitive type, along with some new ones.

Basic Types

  • boolean
  • number
  • string
  • null
  • undefined

Arrays

Arrays can be a little different, they can be written in two ways. The first way is by declaring the type followed by []. The second is by typing 'Array' followed by the type wrapped in '<' and '>'.

  1. let numArr: number[] = [1, 2, 3, 4]
  2. let numArr: Array<string> = ['one', 'two', 'three']

But what if I don't have an array with just a single type? What if I want to use strings and numbers, or even include booleans?

Tuple

Tuples are a type for declaring different elements within an array that has a fixed length. The elements must match types, in the order that they appear exactly.

let tupleExample: [string, number, boolean]

tupleExample = ['Hello', 12, true] // works
tupleExample = [4, false, 'world'] // Doesn't work
Enter fullscreen mode Exit fullscreen mode

Enum

Enums have two purposes: 1. Providing an easy way to give names to sets of numbers. 2. Using a numerical value for a given name. Pretty much the opposite of 1. It does sound a little confusing but is a lot easier with examples. Similar to arrays in JavaScript the first item in an enum is 0, the second is 1, the third is 2, etc. You can change this by manually declaring the positions.

enum Post {
  Draft = 1,
  Published,
  Updated,
}

// Accessing published
let articleStatus: Post = Post.Published  // 2

// Getting the post status by number
let articleStatus: Post = Post[1] // Draft
Enter fullscreen mode Exit fullscreen mode

Any

The "Any" type is great for working with variables that you aren't sure what type they will be. It's mainly used for working with 3rd party applications.

Void

The opposite of any. You'll mainly use this for functions that do not have a return statement.

Null/Undefined

Used for, well, null and undefined. That's really it!

Never

I never really use this one! TypeScript suggests that you use this type for functions that should never ever, ever reach their return statement. A little confusing right? A great example would be a function that's purpose is to throw an error.

Interface

Lastly, there is an interface, this is how we will describe objects. Using an interface is like creating your own type. You can even specify a value as optional so that TypeScript won't get mad at you if your missing something. Adding a '?' before the colon tells TypeScript that the value is optional.

interface Spell {
  name: string;
  level: number;
  components?: boolean;
}

const fireball: Spell = {
  name: 'fireball',
  level: 3,
}
Enter fullscreen mode Exit fullscreen mode

Wow. That was a lot to go through! Yes, there are a lot of types in TypeScript, and I didn't even cover them all but honestly, you just need to know primitives, types/interface, and what you can declare types on. (Variables, Parameters, and Function return values)

Now you're all set to go! Well, at least we're all set to go to write TypeScript in .ts files. We still need to talk about using TypeScript with React in .jsx files.

React Syntax

Components

There are two different ways to write React functional components.

Function declarations

function Navbar(): React.ReactNode {
  return <nav>{...content}</nav>
}
Enter fullscreen mode Exit fullscreen mode

Function expressions

const Button: React.FC = () => {
  return <button>Click Me!</button>
}
Enter fullscreen mode Exit fullscreen mode

Personally I prefer functional expressions as the type is a lot shorter and easy to remember as FC = Functional Component.

Props

Props are objects, right? Use an interface! Note that accepting props like children will use the React.ReactNode type.

interface Props = {
  title: string;
  size: string;
  onClick: () => void;
  children: React.ReactNode;
}
Enter fullscreen mode Exit fullscreen mode

The above onClick function is a callback function and thus doesn't return anything so we will use void.

Hooks

Thankfully hooks are fairly easy too! TypeScript can infer quite a bit. For instance const [name, setName] = useState('') can automatically tell that name is of type String and setName would be (newName: string) => void.

If you need to initiate state as a null value you can declare it using an interface and union operator.

interface User = {
  name: string;
  age: number;
  isLoggedIn: boolean;
}

const [user, setUser] = useState<User | null>(null)
Enter fullscreen mode Exit fullscreen mode

The union "|" can be used to declare types as this or that when your not sure what a type will be, or if a type can change from one or the other. This can be used with regular TypeScript but I try to avoid it as much as possible.

Conclusion

And that's it! Well, not all of it, but it is everything we need to know to start using TypeScript in a React project. There is a lot more that we can do that I haven't discussed like extending interfaces, types VS interface, aliases, etc. So if you want to go in deep you can always check out the TypeScript Handbook along with the TypeScript + React cheatsheet.

So at the beginning of my first tutorial, I had a list of questions that I wanted to answer about TypeScript, and what I wanted from it in order to fully adopt it into my other projects.

Q: What is Static Typing?
A: Static Typing is where your code is checked for accurate typing before runtime. Meaning that each value has the correct type, string = string, number = number, etc.

Q: How difficult is it to get up and running?
A: As we found in my previous tutorial Not very hard at all!

Q: Does it play nicely with React?
A: So far, I would say yes, at least it's definitely easy to get set up. Plus, there aren't that many additional types that are specific to React, which is great. I'll go through building a SpellBook using React and TypeScript in a before/after tutorial.

Q: Can I get rid of prop-types?
A: YES! I mean technically prop-types never does go away? Your, just declaring the types as you code, not at the bottom of the component file.

Questions we still need to answer.

Q: What are the pros/cons of using TypeScript?
Q: How does TypeScript make me a better programmer?

Part 3: Building a SpellBook using React + TypeScript. Coming Soon.

Final Notes

TypeScript can do a lot more than I'm covering in this tutorial, so if you would like to read more you can always checkout out the website.
Another great read is this article written by Joe Previte

Top comments (0)