TypeScript Crash Course #6 - Functions
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
Regular Expressions (RegEx) Tutorial #14 - Matching a Username
Net Ninja
Regular Expressions (RegEx) Tutorial #15 - Email RegEx Pattern
Net Ninja
Regular Expressions (RegEx) Tutorial #16 - Finishing Touches
Net Ninja
GraphQL Tutorial #1 - Introduction to GraphQL
Net Ninja
GraphQL Tutorial #2 - A Birdseye View of GraphQL
Net Ninja
GraphQL Tutorial #3 - Project (stack) Overview
Net Ninja
GraphQL Tutorial #4 - Making Queries (front-end preview)
Net Ninja
GraphQL Tutorial #5 - Express App Setup
Net Ninja
GraphQL Tutorial #6 - Setting up GraphQL
Net Ninja
GraphQL Tutorial #7 - GraphQL Schema
Net Ninja
GraphQL Tutorial #8 - Root Query
Net Ninja
GraphQL Tutorial #9 - The Resolve Function
Net Ninja
GraphQL Tutorial #10 - Testing Queries in Graphiql
Net Ninja
GraphQL Tutorial #11 - GraphQL ID Type
Net Ninja
GraphQL Tutorial #12 - Author Type
Net Ninja
GraphQL Tutorial #13 - Type Relations
Net Ninja
GraphQL Tutorial #14 - GraphQL Lists
Net Ninja
GraphQL Tutorial #15 - More on Root Queries
Net Ninja
GraphQL Tutorial #16 - Connecting to mLab
Net Ninja
GraphQL Tutorial #17 - Mongoose Models
Net Ninja
GraphQL Tutorial #18 - Mutations
Net Ninja
GraphQL Tutorial #19 - More on Mutations
Net Ninja
GraphQL Tutorial #20 - Updating the Resolve Functions
Net Ninja
GraphQL Tutorial #21 - GraphQL NonNull
Net Ninja
GraphQL Tutorial #22 - Adding a Front-end
Net Ninja
GraphQL Tutorial #23 - Create React App
Net Ninja
GraphQL Tutorial #24 - Book List Component
Net Ninja
GraphQL Tutorial #25 - Apollo Client Setup
Net Ninja
GraphQL Tutorial #26 - Making Queries from React
Net Ninja
GraphQL Tutorial #27 - Rendering Data in a Component
Net Ninja
GraphQL Tutorial #28 - Add Book Component
Net Ninja
GraphQL Tutorial #29 - External Query File
Net Ninja
GraphQL Tutorial #30 - Updating Component State
Net Ninja
GraphQL Tutorial #31 - Composing Queries
Net Ninja
GraphQL Tutorial #32 - query variables
Net Ninja
GraphQL Tutorial #33 - Re-fetching Queries
Net Ninja
GraphQL Tutorial #34 - Book Details Component
Net Ninja
GraphQL Tutorial #36 - Styling the App
Net Ninja
GraphQL Tutorial #35 - Making a Single Query
Net Ninja
Build Apps with Vue & Firebase - Udemy Course
Net Ninja
Updated Vue & Firebase Course (Udemy)
Net Ninja
Vue & Firebase Real-time Chat (Preview) #1 - Intro
Net Ninja
Vue & Firebase Real-time Chat (Preview) #2 - Project Structure
Net Ninja
Vue & Firebase Real-time Chat (Preview) #3 - Firestore Setup
Net Ninja
Vue & Firebase Real-time Chat (Preview) #4 - Welcome Screen
Net Ninja
Vue & Firebase Real-time Chat (Preview) #5 - Props in Routes
Net Ninja
Vue & Firebase Real-time Chat (Preview) #6 - Route Guards
Net Ninja
Vue & Firebase Real-time Chat (Preview) #7 - Chat Window
Net Ninja
Vue & Firebase Real-time Chat (Preview) #8 - New Message Component
Net Ninja
Object Oriented JavaScript Tutorial #1 - Introduction
Net Ninja
Object Oriented JavaScript Tutorial #2 - Object Literals
Net Ninja
Object Oriented JavaScript Tutorial #3 - Updating Properties
Net Ninja
Object Oriented JavaScript Tutorial #4 - Classes
Net Ninja
Object Oriented JavaScript Tutorial #5 - Class Constructors
Net Ninja
Object Oriented JavaScript Tutorial #6 - Class Methods
Net Ninja
Object Oriented JavaScript Tutorial #7 - Method Chaining
Net Ninja
Object Oriented JavaScript Tutorial #8 - Class Inheritance
Net Ninja
Object Oriented JavaScript Tutorial #9 - Constructors (under the hood)
Net Ninja
Object Oriented JavaScript Tutorial #10 - Prototype
Net Ninja
Object Oriented JavaScript Tutorial #11 - Prototype Inheritance
Net Ninja
More on: Prompt Craft
View skill →Related Reads
📰
📰
📰
📰
Memoization useMemo()Explained: Why React Doesn’t Need to Repeat the Same Work
Medium · JavaScript
Why Dark Mode Should Not Be a Second CSS File
Dev.to · Hasan Sarwer
Frontend-Only SaaS: The Rise of Static Utility Sites
Dev.to · yobox
Why I Built Yet Another JavaScript Date Picker
Dev.to · RollDate
🎓
Tutor Explanation
DeepCamp AI