Type Predicates Solve This Common TypeScript Error
Key Takeaways
The video demonstrates how to use type predicates in TypeScript to solve a common error that occurs when the type inference fails, specifically when using a function to check if an object has a certain property.
Full Transcript
typescripts inference is incredible probably the best feature in all of typescript but when that inference doesn't work properly it can be incredibly disruptive and difficult to figure out what to do next and this code is the perfect example of when typescript inference fails and how you can actually fix that so in our code here we have a type of user which is just an ID and a name and then we have a type of employee which is the same thing as a user but they also have an email as you can see here we have an array of people which are either a user or an employee you can see we have two users and then we have two employees down here that have actual emails now inside of my code this is actually working and doing inference properly for now as you can see I'm looping through all of my people and right now each person is either a user or they are an employee and then I'm checking hey does this person object have the email field inside of it if the person does have an email field well then we know that they are an employee so we can access the email property and you can see when we hover over this the person object is actually specified as an employee which is why we have access to that email prop when we do our auto complete now in the else case if they don't have that email prop well it means that they are a user so if we hover here you can see that this person is correctly identified as a user so we only have access to name and ID and we don't actually have the email here now this is all working great but a lot of times when you write code like this this if check ends up getting extracted out into a function such as is employee and we pass it in a person so if we create that function real quick is employee this is going to take in a person which is either a user or an employee and we just want to determine hey does this person have the email property so we're going to return if the email is inside the person well we know that that is now an employee instead of a user so if I do this and save my code real quick you'll notice up here we actually have a problem and that's cuz when I hover over a person it now no longer knows that this is a user even though my code is exactly the same the functionality has not changed at all but typescript is no longer able to infer what this person is that's because typescript is not smart enough to look inside of this function to see what's happening it only can inferior code based on what's directly around it not smart enough to look in here and see that this is actually doing that type narrowing for you you instead need to help out typescript by telling it about this type narrowing and this is something called type predicates a type predicate is essentially when you take a function that returns a Boolean and that Boolean specifically is narrowing the type of your object for example we're narrowing this person object down to either a user or an employee so in our case whenever this function returns true we know the type of our person is an employee in those cases all you need to do is where you would normally specify a return type for your function instead you take the variable that you want to narrow the type of in our case person and we want to give it a type by saying that it is some specific type in our case we're saying that this is an employee now when I save you can see my person type here is properly changing to employee and here we can see that the person type is properly being changed to user and that's directly because of this type predicate which is what this called where we're saying that the person is an employee whenever this returns true and if it returns false then that means it's everything except for employee which in our case is just one single value obviously if it could be multiple things it would be all of those things except for the employee so if you ever run into that problem this is how you fix it but there's a few gotes you need to know about type predicates and the main one is that this is essentially the same thing as doing an as casting for example I could mistype this and accidentally say you know what the person is actually a user and now you notice I'm getting errors inside of my code everywhere because now person here is actually being specified as a user or employee and down here my person is actually being typed as never and that's just because user is essentially a subset of the employee if we had these as two very distinct types that weren't related to each other in any way for example instead of making this extend the actual user I changed it to something like this where instead of a name we have an email what I could do is remove the name from these two now these two types are entirely separate from one another and you can see by saying that this is a user when I hover over person you can see that this type is user and when I hover over person down here you can see the type is employee this is entirely incorrect my code is technically correct but typescript doesn't know that because I accidentally made an error down here in my typescript code so that's one thing to watch out for is that you make sure when you do a type predicate that you're 100% certain that this is actually the correct type because this essentially doesn't ask casting that overwrites whatever that type would actually be this is a really handy trick though if you want to take some of that logic especially complicated if checks and track them out into a function which is generally best practice when it comes to clean code now if you want to learn more about typescript including these Advanced features as well as all the more basic features of typescript that you haven't actually spent the time to learn which is causing you to struggle with typescript I'd highly recommend checking out my typescript simplified course it'll be linked down in the description for you it covers absolutely everything you need to know about typescript and it's less than 5 hours long so you can learn everything you need to know about typescript by the end of today again I'm going to link that in the description for you if you enjoyed this video thank you very much for watching and have a a day
Original Description
TypeScript Simplified Course: https://courses.webdevsimplified.com/typescript-simplified/?utm_source=youtube&utm_medium=video-description&utm_term=video-id-Wksz1DnJ2VM
Type predicates are an interesting feature in TypeScript since they cover a very niche use case that can cause type errors if you are not aware of this solution.
📚 Materials/References:
TypeScript Simplified Course: https://courses.webdevsimplified.com/typescript-simplified/?utm_source=youtube&utm_medium=video-description&utm_term=video-id-Wksz1DnJ2VM
🌎 Find Me Here:
My Blog: https://blog.webdevsimplified.com
My Courses: https://courses.webdevsimplified.com
Patreon: https://www.patreon.com/WebDevSimplified
Twitter: https://twitter.com/DevSimplified
Discord: https://discord.gg/7StTjnR
GitHub: https://github.com/WebDevSimplified
CodePen: https://codepen.io/WebDevSimplified
⏱️ Timestamps:
00:00 - Introduction
00:17 - The Problem
02:12 - Type Predicate Basics
03:15 - Type Predicate Problems
#TypeScript #WDS #TypePredicate
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Web Dev Simplified · Web Dev Simplified · 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
Introduction to Web Development || Setup || Part 1
Web Dev Simplified
Introduction to Web Development || Understanding the Web || Part 2
Web Dev Simplified
Introduction to HTML || Your First Web Page || Part 1
Web Dev Simplified
Introduction to HTML || Basic HTML Elements || Part 2
Web Dev Simplified
Introduction to HTML || Advanced HTML Elements || Part 3
Web Dev Simplified
Introduction to HTML || Links and Inputs || Part 4
Web Dev Simplified
Learn Git in 20 Minutes
Web Dev Simplified
5 Must Know Sites For Web Developers
Web Dev Simplified
10 Best Visual Studio Code Extensions
Web Dev Simplified
Learn CSS in 20 Minutes
Web Dev Simplified
How to Style a Modern Website (Part One)
Web Dev Simplified
How to Style a Modern Website (Part Two)
Web Dev Simplified
3D Flip Button Tutorial
Web Dev Simplified
How to Style a Modern Website (Part Three)
Web Dev Simplified
Animated Loading Spinner Tutorial
Web Dev Simplified
How to Write the Perfect Developer Resume
Web Dev Simplified
Animated Text Reveal Tutorial
Web Dev Simplified
Learn Flexbox in 15 Minutes
Web Dev Simplified
Custom Checkbox Tutorial
Web Dev Simplified
Start Contributing to Open Source (Hacktoberfest)
Web Dev Simplified
JavaScript Shopping Cart Tutorial for Beginners
Web Dev Simplified
Responsive Video Background Tutorial
Web Dev Simplified
1,000 Subscriber Giveaway
Web Dev Simplified
How To Prevent The Most Common Cross Site Scripting Attack
Web Dev Simplified
Transparent Login Form Tutorial
Web Dev Simplified
The Forgotten CSS Position
Web Dev Simplified
How to Code a Card Matching Game
Web Dev Simplified
10 Must Install Visual Studio Code Extensions
Web Dev Simplified
Learn CSS Grid in 20 Minutes
Web Dev Simplified
Learn JSON in 10 Minutes
Web Dev Simplified
10 Essential Keyboard Shortcuts For Programmers
Web Dev Simplified
What Is The Fastest Way To Load JavaScript
Web Dev Simplified
Differences Between Var, Let, and Const
Web Dev Simplified
How To Install MySQL (Server and Workbench)
Web Dev Simplified
Learn SQL In 60 Minutes
Web Dev Simplified
How To Solve SQL Problems
Web Dev Simplified
What Are Design Patterns?
Web Dev Simplified
Null Object Pattern - Design Patterns
Web Dev Simplified
Your First Node.js Web Server
Web Dev Simplified
How To Setup Payments With Node.js And Stripe
Web Dev Simplified
How To Learn Any New Programming Skill Fast
Web Dev Simplified
Asynchronous Vs Synchronous Programming
Web Dev Simplified
JavaScript ES6 Arrow Functions Tutorial
Web Dev Simplified
Are You Too Old To Learn Programming?
Web Dev Simplified
JavaScript Cookies vs Local Storage vs Session Storage
Web Dev Simplified
JavaScript Promises In 10 Minutes
Web Dev Simplified
Builder Pattern - Design Patterns
Web Dev Simplified
JavaScript == VS ===
Web Dev Simplified
JavaScript ES6 Modules
Web Dev Simplified
8 Must Know JavaScript Array Methods
Web Dev Simplified
CSS Variables Tutorial
Web Dev Simplified
JavaScript Async Await
Web Dev Simplified
How To Choose Your First Programming Language
Web Dev Simplified
Easiest Way To Work With Web Fonts
Web Dev Simplified
Singleton Pattern - Design Patterns
Web Dev Simplified
Responsive Navbar Tutorial
Web Dev Simplified
CSS Progress Bar Tutorial
Web Dev Simplified
Learn GraphQL In 40 Minutes
Web Dev Simplified
What is an API?
Web Dev Simplified
Learn How To Build A Website In 1 Hour!
Web Dev Simplified
Related Reads
Chapters (4)
Introduction
0:17
The Problem
2:12
Type Predicate Basics
3:15
Type Predicate Problems
🎓
Tutor Explanation
DeepCamp AI