TypeScript Crash Course #9 - Interfaces

Net Ninja · Beginner ·🌐 Frontend Engineering ·2y ago
Skills: API Design60%

Key Takeaways

Introduces interfaces in TypeScript

Full Transcript

okay then my friends so now I want to move on to something much more fun and interesting which kind of opens up a way to define our own custom types and that is interfaces so in a nutshell interfaces are a way to define a certain structure that all data structures can adhere to whether they be classes object literals or even other interfaces now that might sound like gobble de complete nonsense so let's just Dive Right In and do a few examples so let's imagine we have an application that lists a bunch of blog authors on a page and each author would represent or each author would be represented by sorry an object now it might be that you have several author objects and they all need to adhere to a specific object structure for example they might all need a name property which is a string and they might all need an avatar property which could also be a string it could be a URL to a picture or something now we can impose that kind of structure on our objects by making an interface for an author which describes what properties and what type of values those properties should be on an author object now the way we do that is by typing interface first of all and then the name of the interface which I'm going to call Author with a capital A and this capitalization is convention for interfaces it's called Pascal case where each word starts with a capital letter all right so now we're going to open up our curly braces and Define the structure for any object which implements this author interface so we're going to have a name property which is a string and we'll also have an avatar property which is also a string cool so now we have this interface and we can assign it as a type to variables much like we assign strings booleans numbers and arrays as types so let's create a new constant and I'm going to call this constant author one and I'm going to give this a type of author which is the interface which means that this now has to equal an object with these properties so I could put in here we have a name property and that's a string so we'll say this one is Mario and then also we need an avatar property and that's also a string and I will say that's SL image SL mario.png right and now there's no errors if we had a third property like age or something and that was a number then we're going to get an error on this to say look this is not in the interface so let's take that off and now we have this author object which is of type author it adheres to this author interface all right so let's make a new interface now for something else and this is going to be for a post so like a blog post and a post might have a title which is a string it might also have a body which is a string it it might have some tags and those tags could be of type string array and then we could have a created at property and that could be a date and then we could have an author and that could be of type author so we can type properties like this inside other interfaces as our own custom interface type so now if we created a new post I could say constant new post post is equal to something or other and what I will do is type this as a post so now down here we need to add in all the properties we will say the title is going to be something like my first post and then we'll do a body which is something interesting and then after that we will do tags and the tags is going to be a string array so we'll say I don't know gaming um Tech maybe and then after that we will have a created app property now this is a date type which means it must be some kind of date object so we'll just say new date for this and then below that we'll say the author now the author needs to be of author type and we have a constant right here called author one which is of author type so we could use that we could say author one and it allows us and it allows us to do that because this is of type author if we added on any old random object right here then it's not going to allow us to do that it has to adhere to this interface we could write out here so we could add a name and an avatar and that would be fine but I'm just going to use author one instead awesome all right so that's how we can create these interfaces which kind of dictate how an object looks in terms of the properties it has and the values of those properties or rather the types of those properties so now let's have a look at using these interfaces as argument types so what I'm going to do now is create a new function down here and this function will be called create post and it's going to take in as an argument something called post and the type of this will be post as defined right here by this interface so whatever we pass in must be an object object like this kind of thing right here okay so it's going to return nothing so we'll say void right here and then inside I'm just going to log something into the console typically you might do something like save it to a database whatever I'm going to say console.log and we'll do a template string which will say created post and then we'll output the post title so I'll assign curly braces and then post and then if we say dot it's going to know all of the different properties on this post because we said the type of this is a post and it knows that a post has these properties so it gives us good code completion right here so we can say post and then look for the title and we'll output that we'll also say who it's by so we'll say byy and then dollar sign curly braces post then dots and then the author now the author itself is an object and we have an interface for that and we said the type of this author property is author as defined by this interface so if we press dot again over here it's going to know those two properties because it knows it's of author type so we can use the name right here to Output the author name awesome so let's try invoking this function I'm going to say down here create post and invoke it and notice we get an error because it expects an argument so let's pass an argument in which is an object now all I'm going to do is pass in a title property which is a new post title now we still get an error and that's because this must be of type post not just any object so it has to have all of the properties as defined here so instead of that let's just try passing in this new post which we know has all those so new post like so and now we don't get those errors awesome so what I'm going to do is save this and then open up the terminal to see this logged to the console to make sure it's worked and we can see create post my first post which is the title by Mario the author awesome all right so finally let's have a look at how we can use these interfaces with arrays so let me first create a new variable and I'm going to call this posts and I'm going to type this to something so much like we can have arrays that are typed so they can only have certain types of data like strings by saying something like string array we can also do the same with our own custom types using interfaces so we have this post interface face and I could say I want to have an array where only post objects can go inside that array so I could type that as post array like so and to begin with I could set it equal to an empty array but then if I wanted to add items to this array I could only add post objects so let me say posts. push and then if I try to add any old object or even just a string for example that says hello I'm not going to be allowed to do that because that's not post object obviously if I Tred to add an object with the properties like title and maybe also give this I don't know what have we got we've got a body hello again you can see we get an error because this is not a post object we just have a couple of the properties however if I add in the new post which is this thing right here this object that we created that is of type post then it's going to let me do that so new post like so and that works and by the way we don't have to say this is of type post right here for that to work so if I get rid of this like so and just say that new post is equal to this object then these things where we pass new post into the function right here that works and when we pass new post into this push method to add it to this post array that works as well so this doesn't have to be explicitly typed as a post object and also it's not going to infer the type right here because this in typescripts eyes is just an object right it just happens that it conforms to this structure so when typescript is doing checks right here it basically says okay does this thing right here that we pass in this argument does it conform to this interface right here does it have all the same properties and are those property types the required types and in this case yes they are but if I changed one of the types right here like if I changed this to a number like three for example then this is not going to work and this is not going to work right because it recognizes now that these properties and types of these properties are not the same as defined right here so let me just hover over this and you can see that this is not inferring it as a post right that's important it's not inferring it as a post we have to explicitly say when we're using an interface that this is a post if we want to give it that definite type okay but nevertheless if we take this off this object still adheres to this structure and so we're allowed to pass it into functions where we declared that it must be of type post or that we have an array of type post inside that array and we can add them to it okay so there we go my friends that's the basics of interfaces it's a really powerful feature that allows us to Define these kind of custom types of data now in the full Master Class course we'll go into much more detail about interfaces how they can be extended and work alongside other data structures like classes this was very much scratching the surface of what they can do for us in this video so if you want to learn more about them then I'm going to leave a link to the full Master Class down below the video

Original Description

In this TypeScript tutorial series, you'll learn what TypeScript is, and how to get up and running with it quickly. 🚀🔥🥷🏼Get access to the whole TypeScript Masterclass course on Net Ninja Pro: https://netninja.dev/p/typescript-masterclass 📂🥷🏼 Access the course files on GitHub: https://github.com/iamshaunjp/typescript-masterclass 💻🥷🏼 Learn more about Next.js with the Next.js Masterclass: https://netninja.dev/p/next-13-masterclass 💻🥷🏼 Learn JavaScript with the Modern JavaScript series: https://netninja.dev/p/modern-javascript-from-novice-to-ninja 🔗🥷🏼 TypeScript docs - https://www.typescriptlang.org/download 🔗🥷🏼 Install Node.js - https://nodejs.org/en 🔗🥷🏼 VS Code - https://code.visualstudio.com/
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Net Ninja · Net Ninja · 0 of 60

← Previous Next →
1 Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
2 Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
3 Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
4 GraphQL Tutorial #1 - Introduction to GraphQL
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
5 GraphQL Tutorial #2 - A Birdseye View of GraphQL
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
6 GraphQL Tutorial #3 - Project (stack) Overview
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
7 GraphQL Tutorial #4 - Making Queries (front-end preview)
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
8 GraphQL Tutorial #5 - Express App Setup
GraphQL Tutorial #5 - Express App Setup
Net Ninja
9 GraphQL Tutorial #6 - Setting up GraphQL
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
10 GraphQL Tutorial #7 - GraphQL Schema
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
11 GraphQL Tutorial #8 - Root Query
GraphQL Tutorial #8 - Root Query
Net Ninja
12 GraphQL Tutorial #9 - The Resolve Function
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
13 GraphQL Tutorial #10 - Testing Queries in Graphiql
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
14 GraphQL Tutorial #11 - GraphQL ID Type
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
15 GraphQL Tutorial #12 - Author Type
GraphQL Tutorial #12 - Author Type
Net Ninja
16 GraphQL Tutorial #13 - Type Relations
GraphQL Tutorial #13 - Type Relations
Net Ninja
17 GraphQL Tutorial #14 - GraphQL Lists
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
18 GraphQL Tutorial #15 - More on Root Queries
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
19 GraphQL Tutorial #16 - Connecting to mLab
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
20 GraphQL Tutorial #17 - Mongoose Models
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
21 GraphQL Tutorial #18 - Mutations
GraphQL Tutorial #18 - Mutations
Net Ninja
22 GraphQL Tutorial #19 - More on Mutations
GraphQL Tutorial #19 - More on Mutations
Net Ninja
23 GraphQL Tutorial #20 - Updating the Resolve Functions
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
24 GraphQL Tutorial #21 - GraphQL NonNull
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
25 GraphQL Tutorial #22 - Adding a Front-end
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
26 GraphQL Tutorial #23 - Create React App
GraphQL Tutorial #23 - Create React App
Net Ninja
27 GraphQL Tutorial #24 - Book List Component
GraphQL Tutorial #24 - Book List Component
Net Ninja
28 GraphQL Tutorial #25 - Apollo Client Setup
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
29 GraphQL Tutorial #26 - Making Queries from React
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
30 GraphQL Tutorial #27 - Rendering Data in a Component
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
31 GraphQL Tutorial #28 - Add Book Component
GraphQL Tutorial #28 - Add Book Component
Net Ninja
32 GraphQL Tutorial #29 - External Query File
GraphQL Tutorial #29 - External Query File
Net Ninja
33 GraphQL Tutorial #30 - Updating Component State
GraphQL Tutorial #30 - Updating Component State
Net Ninja
34 GraphQL Tutorial #31 - Composing Queries
GraphQL Tutorial #31 - Composing Queries
Net Ninja
35 GraphQL Tutorial #32 - query variables
GraphQL Tutorial #32 - query variables
Net Ninja
36 GraphQL Tutorial #33 - Re-fetching Queries
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
37 GraphQL Tutorial #34 - Book Details Component
GraphQL Tutorial #34 - Book Details Component
Net Ninja
38 GraphQL Tutorial #36 - Styling the App
GraphQL Tutorial #36 - Styling the App
Net Ninja
39 GraphQL Tutorial #35 - Making a Single Query
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
40 Build Apps with Vue & Firebase - Udemy Course
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
41 Updated Vue & Firebase Course (Udemy)
Updated Vue & Firebase Course (Udemy)
Net Ninja
42 Vue & Firebase Real-time Chat (Preview) #1 - Intro
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
43 Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
44 Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
45 Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
46 Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
47 Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
48 Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
49 Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
50 Object Oriented JavaScript Tutorial #1 - Introduction
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
51 Object Oriented JavaScript Tutorial #2 - Object Literals
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
52 Object Oriented JavaScript Tutorial #3 - Updating Properties
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
53 Object Oriented JavaScript Tutorial #4 - Classes
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
54 Object Oriented JavaScript Tutorial #5  - Class Constructors
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
55 Object Oriented JavaScript Tutorial #6 - Class Methods
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
56 Object Oriented JavaScript Tutorial #7 - Method Chaining
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
57 Object Oriented JavaScript Tutorial #8 - Class Inheritance
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
58 Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
59 Object Oriented JavaScript Tutorial #10 - Prototype
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
60 Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja

Related Reads

📰
Part 7B — Section 2 — React Event Handling Explained: Forms, Event Object & User Input.
Learn React event handling for forms and user input to improve your frontend skills
Medium · JavaScript
📰
Stop Using window.resize for Everything: A Practical Guide to the ResizeObserver API
Learn to replace window.resize with the ResizeObserver API for more efficient and effective resize event handling
Medium · JavaScript
📰
Rendering Lists and Handling Events
Learn to render lists and handle events in web development to create interactive user interfaces
Dev.to · Silas
📰
React Explained: JSX, Components, Virtual DOM & Diffing Algorithm
Learn the fundamentals of React, including JSX, components, virtual DOM, and diffing algorithm, to build fast and interactive user interfaces
Dev.to · Saravanan Lakshmanan
Up next
Elementor Angie Ai Plugin Tutorial
Quick Tips - Web Desiign & Ai Tools
Watch →