DEV Community

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

Posted on

9 4

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay