DEV Community

Cover image for Upgrade your React game with TypeScript: More on Types
Elizabeth Villalejos
Elizabeth Villalejos

Posted on

Upgrade your React game with TypeScript: More on Types

Types are essentially, defining the data type of our variables.

interface Eli {
  name: string;
  age: number;
  likes: string[];
  coffeesDrankToday?: number[]
}

For declaring arrays, we state the type of data the array has to contain and then use the brackets. Another way to declare them can be this way likes: Array<string>.

Also, remember that you can make a variable optional within an interface writing a ? before the data type.

But sometimes, we need something a bit more complex.

My Chi Dulce, contemplating her choices

Dulce, contemplating her type choices

Maybe we need to load an interface as an empty object, which we can do like this daily: <YourInterfaceHere>{}.

Sometimes we don't know what kind of data we're dealing with when using an API or maybe we want to opt-out of type checking for a particular variable. In this case, we can use any. The downside of using it is that we're not taking advantage of what TypeScript has to offer us so it's highly discouraged to use.

The opposite of any is using void, which is the absence of all types at all. This is common in functions that don't return a value.

You can even create your own types from an interface!

export interface LoadDayAction {
    type: string;
    payload: Day;
}

export interface ErrorLoadAction {
    type: string[];
    payload: Error;
}

export type DailyTypes = LoadDayAction | ErrorLoadAction;

Now you could use LoadDayAction or ErrorLoadAction to define another variable.

You can read up further on types here.
_

I hope you found this helpful, stay safe and please remember to take a break.

Got something to add? Please feel free to reach out for any question, comment, meme or dog photos swap.

Top comments (0)