TypeScript Crash Course #6 - Functions

Net Ninja · Beginner ·🌐 Frontend Engineering ·2y ago

Key Takeaways

This video series covers the basics of TypeScript, specifically focusing on functions, including specifying argument types and return types, using type annotations, and understanding function types and return type inference. The course utilizes TypeScript as the primary tool for demonstration and provides hands-on coding examples.

Full Transcript

okay then so now I want to talk about functions in typescript and we're going to focus on two different parts of a function first of all the arguments in a function and then also the return value of a function right so I've got a function here already set up which takes in two arguments A and B and it Returns the sum of those arguments and so far this looks identical to a function in regular JavaScript except we get these little errors right here where the arguments are and that's because we're not telling typescript what types these arguments should be now in regular JavaScript we could invoke this function and pass in any types of data as arguments and it wouldn't cause any errors or bugs until runtime right so I could pass in a string and a Boolean into this function and we find out if there were any errors or bugs with that when we come to run the code it's not going to tell us beforehand but in typescript we need to specify the types of arguments we want this function to accept and then when we invoke that function it won't let us pass in the wrong types and that's going to result in less runtime errors and bugs because we've already fixed the problem ahead of time so then let's give these arguments a type so we'll say that a must be a number and B must also be a number and we can also explicitly tell typescript what type of value this function must return by adding a colon after the parentheses and then adding the type itself in this case I want the function to return a number number so I'll write a number and that means if I try to return a different type of value now from the function then it won't let me and I'm going to see an error telling me that this is the wrong return type all right okay cool all right so now let's make another function but this time I'm going to create the function as an arrow function just to show you both types we've got a regular function right here now we'll do an arrow function so to do that we can say const give the function a name we'll say subtract two numbers we set that equal to a function this time and we're going to take in two arguments again we'll call them A and B but they can be whatever you want and they're both going to be numbers so we'll say the type of a is a number and then the type of B is also a number this is going to return a number so again colon after the parentheses then number and then because this is an arrow function we use the arrow and then open up the curly braces so we're pretty much writing the function in the same way it's just that this is an aror function and this isn't all right now currently notice this error and it says right here a function whose declared type is neither undefined void or any must return a value so basically we're saying here we want to return a number but we're not actually returning anything yet so let's return and then it's going to be this time a minus B and now that error goes away because we are returning a number all right so let's try invoking these functions I'm going to say add to numbers like so I'm going to pass in two numbers so three and 9 for example and this works we don't get any errors now but if we try to pass in something that's not a number for example a string n then this is not going to work and if I try to pass in something different here like a Boolean this isn't going to work either now the error is going to weigh here and that's just because it's reading this first but if we get rid of this error by changing it back to a number then it moves on to the next error it finds and it says this one is a string it should be a number so let's change this back to a number and everything works okay the next one subtract two numbers again if we invoke that then I can pass in two numbers and that works fine however if I change one of these to a string it's not going to work awesome so that's really helpful hopefully you can see the benefit of typing these out because then when we come to invoke these functions at a later point in time it's going to minimize the errors we make by making sure we pass through the correct types of data that that function expects right so let me do another example I'm going to going to create another function this time called add all numbers and inside this function we'll accept an argument called items which will be a number array so number then square brackets now this function is going to look at this items array and it's going to take all the numbers inside it add them all up to a total and log that total to the console now we're not specifying a return type right here and I'll explain why shortly for now I want to paste in a line of code which grabs us that total so we take the items which is an array and we use this array method reduce which we can do by the way let me just grab this right here we can use array methods because this is an array typescript knows this is an array so it gives us access to all of the different array methods and properties right here if we tried to use something that wasn't an array method then it would give us an error but this is an array method so we can use it so we use that reduce method which FES a function for each element inside this array and it basically adds them all up with a starting position of zero and it returns that total right here okay so we have that total value now what I'd like to do is log that to the console so console do log and then we will say total okay now the reason I've not specified a type right here to return is because we're not returning anything so if I come down here and say add all numbers and then pass in an array of numbers so I will say 5 7 9 11 3 2 1 then the return type of this if you take a look is void we don't get a return and this void type means nothing is going to be returned from this function now we can't explicitly type that right here void and that's going to do the same thing for us except this time it's not inferred where we didn't have this it infers the return type but when we explicitly type it it then it's explicit now if we were to return the total then this is not going to be valid because now this is not void this is actually a number so we would have to specify a number right here to say the return type is a number but again if we don't specify that return type typescript is going to infer it looking at the type of this so if we hover over this function we can see it's infer the type of number as a return type okay I'm going to go back to void and not return anything all right then so now this all works let's try previewing this in a terminal because we do log it out so hopefully you've still got those watch commands running in the terminal I'm just going to open this because I have and we can see the node one has restarted this file and we can see this output right here 38 which is the total I think of all these numbers awesome okay so there's one more thing I quickly want to mention in this video and we have already touched upon it and that is return type inference so so I'm going to paste in a function right here and this function is called format greeting and it takes in two arguments a name which is a string and also a greeting which is a string now inside here we return basically a template string which combines these two so it takes the greeting first and then the name so this could be good morning and this could be Mario and it could be good morning Mario that we return which is a string right now we're not actually explicitly saying what the return value is right here but Ty script is going to infer it for us so I could say const result is equal to format greeting like so I'm going to pass in the two arguments so the name which is Mario and I'll just say hello right here for the greeting and now if I hover of a result it's going to say that this result is of type string so it inferred what value type is being returned right here and it knows what value type is being returned because this is a string and it knows it's a string because we're explicitly returning a template string right we're not returning a variable that it doesn't know we're saying it is a template string right here so this is the same as just putting up here string it infers that type but a lot of the time we don't need to put that up here so that's pretty much it for functions hopefully now you can see the benefit of typing these arguments and also by the way just when it comes to inferred types if we don't explicitly say the type right here so if I don't say string right here then basically I can return any type over here so if I wanted to here I could say return 10 and it's going to let me however this function really shouldn't be returning a number probably so um it sometimes is beneficial to say what the return type should be if you want to enforce that down here because now you see we get an error because we're not returning a string all right cool so like I said there's functions in action in the next video we're going to look at another typee called the any type

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

This video teaches the fundamentals of functions in TypeScript, including how to specify argument and return types, use type annotations, and understand function types and return type inference. By mastering these concepts, developers can write more robust and maintainable code. The course provides a comprehensive introduction to TypeScript functions, making it an ideal resource for beginners.

Key Takeaways
  1. Specify argument types and return types in a function
  2. Use type annotations to define a function with specific argument and return types
  3. Use arrow functions to define a function with type annotations
  4. Create a function with typed arguments
  5. Use array methods like reduce with typed arrays
  6. Log the result of a function to the console
  7. Specify the return type of a function using the return type keyword
  8. Return a template string to infer return type as string
  9. Explicitly define return type to enforce type safety
💡 TypeScript's type system helps prevent runtime errors by ensuring that functions are called with the correct types and return the expected types, making it a valuable tool for building robust and maintainable applications.

Related Reads

Up next
How to Use Semrush Keyword Magic Tool with ChatGPT to Make Money
Grow with Will - SEO, Sales & Entrepreneurship
Watch →