DEV Community ðŸ‘Đ‍ðŸ’ŧðŸ‘Ļ‍ðŸ’ŧ

Dev By RayRay
Dev By RayRay

Posted on • Originally published at hasnode.byrayray.dev on

How To Use A TypeScript Interface?

Pizza interface

An interface is a blueprint for an Object. It tells you which properties there are, which are required and optional and which type of data they hold.

TypeScript has become more popular than ever. For me it was not love at first sight, but now we are connected. I don't start a project without TypeScript! 😅 So if you experience the same feelings, your not alone ðŸĪ—

Most of the models in TypeScript are a combination of interfaces and classes. An interface is a blueprint of a class or object. In this IPizza interface, we define all the properties a pizza has. In each property, we define what kind of data type the information is.

Every property that is defined in an interface is required. If you want to make it optional, you must use the ? . For example, propertyName?: string if we define this property in an interface, it's optional. TypeScript won't give you an error if the property is missing in an Object. On the other hand, if a property is required, it will give an error if it is missing.

When a property is not defined in an interface you will get an error from the TypeScript compiler because the data is not according to the blueprint.

divider-byrayray.png

Example

We can all come up with properties for a pizza.

  • Name
  • Slices (the number of slices)
  • Toppings
  • Price
  • Cheesecrust
  • Vegan
  • Vegetarian

Lets put them in the interface and decide what kind of data type they are.

interface IPizza {
    name: string;
    slices: number;
    toppings: string;
    price: number;
    cheescrust: boolean;
    vegan?: boolean;
    vegetarian?: boolean;
}

Enter fullscreen mode Exit fullscreen mode

The example above shows an interface for our pizza. We gave all the properties a single data type. Now we can create our Pizza object and use the interface to ensure it has the correct properties.

const pizza: IPizza {
    name: 'Pizza BBQ',
    slices: 6,
    toppings: 'Tomato sauce, BBQ sauce',
    price: 15,
    cheescrust: true
}

Enter fullscreen mode Exit fullscreen mode

Now the pizza is according to the interface. The interface is now a form of data validation. If we would add properties that are not in the interface or properties with wrong data types, the TypeScript will give errors.

const pizza: IPizza {
    name: 'Pizza BBQ',
    slices: 6,
    toppings: ['Tomatosauce', 'BBQ sauce'],
    price: 15,
    cheescrust: true,
    meat: true
}

Enter fullscreen mode Exit fullscreen mode

With this object, you will get errors! 👇 (Check it onCodeSandbox for yourself)

1_2lVYUioEXcbN31E8FZg6ww.png

divider-byrayray.png

Multiple values

But what if we want an array of strings or numbers to give our toppings or sizes? We can do that pretty quickly; write string[] or number[] in the interface.

interface IPizza {
    name: string;
    slices: number;
    toppings: string[];
    price: number;
    cheescrust: boolean;
    sizes: number[];
    vegan?: boolean;
    vegetarian?: boolean;
}

Enter fullscreen mode Exit fullscreen mode

Now our pizza object is valid.

const pizza: IPizza {
    name: 'Pizza BBQ',
    slices: 6,
    toppings: ['Tomatosauce', 'BBQ sauce'],
    price: 15,
    cheescrust: true,
    vegan: false,
    vegetarian: false,
    sizes: [0, 1, 2, 3, 4]
}

Enter fullscreen mode Exit fullscreen mode

If we want to type an Array with multiple pizza objects, we can do that the same way with IPizza[].

const pizzaArray: IPizza[] = []

Enter fullscreen mode Exit fullscreen mode

divider-byrayray.png

Conditional values

Sometimes, you will say that a property can be a string or a null. In those cases, we use the pipe | to show that it is both.

// IPizza properties with an array of values.
interface IPizza {
    name: string;
    slices: number;
    toppings: string[];
    price: number;
    cheescrust: boolean | null;
    sizes: number[];
    vegan?: boolean;
    vegetarian?: boolean;
}

Enter fullscreen mode Exit fullscreen mode

For example, with the cheescrust it is optional but can be a boolean or null.

const pizza: IPizza {
    name: 'Pizza Tuna',
    slices: 8,
    toppings: ['Tomatosauce'],
    price: 11.99,
    cheescrust: null,
    vegan: false,
    vegetarian: false,
    sizes: [0, 1, 2, 3, 4]
}

Enter fullscreen mode Exit fullscreen mode

So with the Pizza Tuna, we say we dont want to offer cheese crust, so we give it a value of null.

divider-byrayray.png

Thanks!

hashnode-footer.pngAfter reading this story, I hope you learned something new or are inspired to create something new! ðŸĪ— If so, consider subscribing via email (scroll to the top of this page) or follow me here on Hashnode.

Did you know that you can create a Developer blog like this one, yourself? It's entirely for free. 👍💰🎉ðŸĨģðŸ”Ĩ

If I left you with questions or something to say as a response, scroll down and type me a message. Please send me a DM on Twitter @DevByRayRay when you want to keep it private. My DM's are always open 😁

Top comments (2)

Collapse
mbarzda profile image
Martynas Barzda

As long time developer with TypeScript, I would suggest:

  1. Interfaces do not need "I" prefix in TypeScript, because there is implements clause, which means that you are using an interface. This pattern is obsolete and pollutes codebase;
  2. If you want make your object stricter, use type instead interface. That's why TypeScript is for. Let's leave interface just for classes. If your app is not written in OOP, none of interfaces should be in your codebase.
Collapse
devbyrayray profile image
Dev By RayRay Author

@mbarzda thanks for the extra details 🙏.

Many codebases I've worked with use the I as a prefix. But I agree with your reason why it's not a smart idea ðŸ’Ą.

And as you said, let's leave the interface for a class, makes perfect sense. So that's making it much more clear when to use a interface or a type.

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.