September 6th, 2021 × #TypeScript#StrictMode#WebDev
Hasty Treat - TypeScripts Strict Explained
Wes and Scott discuss the different strict mode settings in TypeScript and why they can prevent bugs.
- NoImplicitAny prevents TypeScript from inferring any for untyped variables
- NoImplicitThis requires explicitly typing this in functions
- StrictFunctionTypes prevents assigning mismatched function types
- AlwaysStrict enables strict mode to prevent redeclaring variables
- Strict mode can prevent certain JavaScript edge cases
- Strict mode prevents creating undeclared variables
- StrictNullChecks requires null checking before property access
- StrictBindCallApply enables type checking on bind, call and apply
- StrictPropertyInitialization requires setting class properties in constructor
- UseUnknownInCatchVariables sets catch variable types to unknown instead of any
Transcript
Announcer
Monday. Monday. Monday.
Announcer
Open wide dev fans. Get ready to stuff your face with JavaScript, CSS, node modules, barbecue tips, get workflows, breakdancing, soft skill, web development, the hastiest, the craziest, the tastiest TS, web development treats coming in hot. Here is Wes, Barracuda, Boss, and Scott, El Toroloco, Tolinski.
Scott Tolinski
Welcome to Syntax. In this Monday, hasty treat, we're gonna be talking about TypeScript.
Scott Tolinski
Strict.
Scott Tolinski
Type you could say it's type strict, maybe. Type strict. Oh, I like that.
Scott Tolinski
Type type Type Type Type Type Type And this episode this is gonna be a lot of fun. My name is Scott Talinski. I'm a developer from Denver, Colorado. And with me, as always, is Wes Bos.
Wes Bos
Hey, everybody. I'm a developer from Hamilton, Ontario.
Scott Tolinski
Nice. I love it. Very nice. Hamilton Tigers, home of the Hamilton Tigers. Tiger cats. Yeah. So this episode is sponsored by 2 amazing companies. We're talking about Sanity, and LogRocket. Wes, do you wanna talk about Sanity, and I'll talk about LogRocket?
Wes Bos
Sanity is a unified content platform that powers better better digital experiences. What does that mean? Well, they are a pretty slick service that you can use to build a, They say digital experience, but it's a CMS that is wicked.
Wes Bos
So you sign up for Sanity. It's a hosted service, but the Sanity Studio is something that you can run locally and run on your computer, and it just talks to sanity via APIs. And that means you've got full control Over custom inputs and things like that, but you don't give up. Like, it's it's really the best of both worlds. You get all the stuff. Like, you could see who's editing or who edited something, or have custom workflows where you you save something, but it has to be approved by somebody else and really just, like, a super flexible Content platform. Check it out. Sanity.i0forward/ syntax, double the free usage tier if you use that URL. Thank you, sanity, for sponsoring. This episode is all sponsored by
Scott Tolinski
log rocket@logrocket.com is the perfect place to see all of your errors and exceptions happen, and I'm talking about actually seeing them with a scrubbable video replay that you get your network requests, you get your console log, did all that stuff and more, and the ability to actually see what's happening in your user When the user clicked on the thing and broke the thing and, well, now you're not just pawning through errors, but you're pawning through a video that shows you what happened. It's endlessly impressive. Give it a try at logrocket.comforward/syntax, and you will get 14 days for free. Thank you so much for LogRocket for Sponsoring. Alright. Let's get into TypeScript script TypeScript script. And, we're gonna be talking about what it is, why you might use it, and, You know, what are some of the config options that it enables? So, Wes, do you wanna kick this one off?
NoImplicitAny prevents TypeScript from inferring any for untyped variables
Wes Bos
Yeah. So their TypeScript Has a config TS config file, and in that, you set all of your TypeScript settings. And there's one that's called strict, and there's sort of a blanket flag for all of the different strict values. So when you turn strict to true, it actually turns on 1, 2, 3, 4, 5, 6, 7, 8 8 different strict flags, and they are also saying that there may be more in the future. So by turning that on, you You kinda have to be careful when you bump a major version of TypeScript. So the first one we have here is no implicit any, and we're gonna kinda rattle through them. I've put the more more common ones up at the top here, and then we'll get into the, the ones that I don't run into as often. But probably the most Common one is no implicit any, and what that means is that anything in TypeScript It can be anything. There's an any type in in TypeScript, dude. When you set something to be any, it can be literally any type. It could be a number. It could be a string. It could be a sandwich. You name it. So TypeScript, when you are typing a function or adding two numbers together or something like that, TypeScript will try to infer the type. So if you've got a number and another number and you add them together using math, TypeScript will infer that, okay. Well, those 2 things are numbers. You did some math with them, so we're going to have a number. So it's It's not necessary to type adding 2 plus 2 together because it it already knows it can infer it. However, sometimes in TypeScript, you TypeScript won't be able to infer the type from the whatever method or function is running, And that's the case where it gives it an any type. Now in TypeScript, there are often use cases for giving something an any. We have a whole There's a podcast about nothing.
Wes Bos
You can go and listen to that, but that is an explicit any. So you could explicitly Type it as any, like you type the keys a n y, but when you don't type it, it's implicitly inferred.
Wes Bos
That's where you can run into bugs. It could might be a mistake. It might be something somewhere else in your code That has maybe a function has changed, and now it's returning any, and you forgot to type it. And that's where it gets risky. So no implicit any is probably the most common.
NoImplicitThis requires explicitly typing this in functions
Wes Bos
Most people turn these all on, but if if people are going piecemeal, most people turn the this one on. Yeah. Because I think without NoImplicitAny,
Scott Tolinski
you're really losing a ton of benefits of TypeScript. It's definitely flying blind in many regards. And Yeah. If you're using TypeScript, even though it can be annoying when you have all of these type errors and whatever, It can be annoying, but that doesn't mean that you just turn it off. It means that you have to fix the stuff is is really what it comes down to. You probably have a issue somewhere else. Yeah. So, I mean, no implicit any. You know, this is one that I would always recommend having on, especially, you know, if you're you're getting into TypeScript from the start, Get used to typing your n e's or your implicitly typed n e's. But there's also the, no implicit to this. As in this must be Explicitly typed as well so that TypeScript knows what this is, and I say that in the JavaScript at this. So that in the same regard, just Like the no implicit any no implicit this.
Scott Tolinski
That way, your TypeScript compiler is aware of the context in which you're working in. You can get yourself into trouble where if you
StrictFunctionTypes prevents assigning mismatched function types
Wes Bos
have, like, a callback function and you have this inside of it and then that callback function is being run on something else, This might be some other type. Right? So if you explicitly type it, both your function will be more secure, but, also, if you try to use that Callback function on something else where this doesn't line up, then TypeScript will yell at you. Yeah. Totally.
Wes Bos
Next one we have here is strict function types. If you have a, a function that is typed to accept, like, let's say, a string, and then you have another type where that is typed as a function that takes in a different number of values, like, say, if the doc shows a string or a number and your function is taking in a string, If you try to assign that that type to another function, it's gonna yell at you and say, okay. These 2 things are not lining up. And I believe That is you know, you get that error where there's not significant enough overlap in TypeScript, where you you have a type, a And then it's expecting another one. It says, alright. Well, what you gave me and what I was expecting, there is no significant overlap. I believe that is the same thing.
Scott Tolinski
This is not specifically one that I run into all the time. Yeah. It is funny because the no implicit any is the one you you probably hit the most out of all of these. CSF. Here's another one called always strict, which always turns on strict mode, and you can't, do things like redeclare
AlwaysStrict enables strict mode to prevent redeclaring variables
Wes Bos
var variables. And and this is Script strict mode. Right? Yeah. This is not TypeScript. This is use strict at the top of your document. Most people probably are not typing this Because ES modules are automatically strict mode. Right. But this just always assumes that you are in strict mode, which is a great idea.
Strict mode can prevent certain JavaScript edge cases
Scott Tolinski
It's funny because they we're dealing with 2 different stricts here. You know, you can always strict. We're like, yeah. I I turned on strict mode. Wouldn't it always be always strict? Like, yeah. This is definitely referring to the JavaScript.
Wes Bos
Another thing is if you have a variable that you did not declare in regular JavaScript, that's fine. You could just say Wes equals cool, and that would be that would be valid. But here in strict mode, it would say, you never Declare it of our variable. I remember when we had a oh, we haven't done Stumped in a while. Remember we had an episode of Stumped Yeah. Where we had a we had to say what strict mode was. Some people might not even ever heard Stumped because it's been so long. No. We couldn't. It was hard for us to figure out what they were. The only thing I remember is the variables.
Strict mode prevents creating undeclared variables
Wes Bos
There's some other weird stuff, but this is just, like because we've been using strict mode for probably 6 years now, 7 years, It's it just you just think that's JavaScript. Right? You don't know these weird edge cases where you could possibly
Scott Tolinski
have bugs. That's JavaScript, baby. Yeah. I I agree. I I think we'll we'll put on a, a stump for when we get back from our little vacay here. So Yeah. Yeah. We'll we'll come back, and we'll be, like, all fresh and ready to go, and then we'll do an episode of Stumped and then kill both of our spirits right out of the gate.
Wes Bos
Next one we have here is strict null checks. This is kind of annoying to a lot of people because they're used to sort of just winging it in, winging it in their JavaScript, but what strict null checks does is it makes sure that you actually have a value before go ahead and accessing a value or a method on it. So imagine you, have an array of people, And you filter that for people who start with w, or you find people in that array who have the name Wes, Or you are query selectoring a element with the class of Wes. There's a possibility in all of those use cases that Nothing is returned because the filter, the find, or the query selector didn't find anything that matched what you were looking for.
StrictNullChecks requires null checking before property access
Wes Bos
And In JavaScript, most cases, you're just like, alright. Let's just just assume that it's there. Strict null checks will make sure that you check if it's there. So you say, if Something exists, then go ahead and do it. And what I do in most cases, if I say I say, if it doesn't exist, return. Or if it doesn't exist, log something out or throw an error, and then go ahead. Because I hate having to wrap all of my code in an if statement, So I check for the opposite and then exit out of the function and then can below that, you can continue on without being inside of a if block. Yeah. Totally.
Wes Bos
The oh, the nested what's the I always forget the name of it. What's the thing, nested property checking, where you put the question mark in front of everything?
Scott Tolinski
Nested.
Wes Bos
You optional? I don't know. I don't know. Optional chaining. You got it. There you go. The optional chaining is really handy because If you've got, like, 8 levels deep, strict null checks will make you check for every level deep. So putting the question mark at the end of ever that one of those properties We'll get you out of that pickle. And next 1 is strict, bind,
StrictBindCallApply enables type checking on bind, call and apply
Scott Tolinski
call, apply. Now I I don't actually know what this one is. Neither do I.
Wes Bos
Very rarely do I actually need to use like, when's the last time you've used bind, call, apply?
Scott Tolinski
I don't often do it. It's funny because I just I mean, bind.
Scott Tolinski
I don't know about call apply as much, Right. I've just been doing a little bit more vanilla JavaScript with web components, and I've had to use it all a little bit more, but, yeah, not often, especially my my current workflow.
Wes Bos
Yeah. So bind call apply will either call or return a function that are like, I always like This thing, they're loaded with your variables already. So you could bind a function with the value and then call it later on, and it will Sort of, like, have those, like, batteries included, and what will happen is if you bind call apply a function, it will do a type check Against the values that you are using, and and that makes sense because because that's like
Scott Tolinski
that's like saying, should you check that your functions have the right types When you're calling them Yeah. So you should always have this one turned on. Yeah. I never run into this. It's funny because I I have strict bow turn on. It's like, I only learn about the things n. When I run into the error and then you Google the error, and you're like, okay. How do I fix this thing? The best way to learn. Yeah. Right.
Wes Bos
Next one here is strict property initialization.
Scott Tolinski
And this one is specifically for classes is what I'm saying. So, when set to true, TypeScript will raise an error when the when a class property was declared but not set in the constructor.
StrictPropertyInitialization requires setting class properties in constructor
Scott Tolinski
So basically, you have a type on a class that says here's a class property, but then in your constructor, it's not being said. It doesn't exist. There's no default value being set via that Structure, it's going to, be upset that TypeScript has no initializer will be the error that it gives you. No element initializer and is Not definitely assigned in the constructor. So seems like if you're working in classes, which I don't really it is funny again. Another situation where I've been working in classes has been web components. Yeah. So, you know, outside of the React function bubble, some of these things seem like they're probably much more useful, especially, I mean, given that I know, like, Angular uses a lot of classes. So this one seems like it would pop up quite a bit there. Last 1 we have here is use unknown in catch variables. This is introduced in TypeScript before.
UseUnknownInCatchVariables sets catch variable types to unknown instead of any
Wes Bos
When you catch a, like, let's say, a promise or something like that, you you catch That the error that you get was initially any, but now it is unknown.
Wes Bos
And with unknown, that forces you to Check if something is an instance of an error because I guess there's cases where that could potentially be an issue. So I've been running strict mode for almost a year now, and I've not Run into that specific one. Yeah. I have neither. Yeah.
Wes Bos
So that is strict mode. This is a frustrating thing. I recommend when you're learning TypeScript, just turn it on, And then you will run into all these things where it's like, this is wrong. This is wrong. This is wrong. This is wrong. And that's really a good way to understand Why? Like, I can see myself included. Sometimes you're like, this is silly. I'm gonna turn this off. But if you really look into it or or keep it on, You can understand that TypeScript is trying to catch some possible weird edge case bugs that you may not be thinking of at this moment,
Scott Tolinski
and it's trying to it's trying to help you out instead of make your life awful, which is sometimes what it it feels like. Yeah. It's it's trying to help you out. That's definitely it. It is funny because it does feel like it's trying to make your life not great for a while, but you get you do You power through it. You you get used to these TypeScript errors. You eventually learn how to read through the matrix and the TypeScript code. You can solve them quickly, And then you'll be very, very happy once you do. Because let me tell you, as somebody who's doing what could be a major refactor right now, then I I think that's an evergreen statement. So Depending on whenever you're listening to syntax, the fact that I'm doing a major refactor is just an evergreen statement. But let me tell you, Nothing is better than having that that safety net of TypeScript just being there. Like, I'm on the I'm on the trapeze. I'm walking the tightrope. I'm like, oh, and TypeScript's like, don't worry. I got you. If you fall Yeah. I got you. Yeah. So, you know, strict mode definitely is a go for me,
Wes Bos
and definitely highly recommend Keeping all of this stuff on regardless of how annoying it can be. You can also turn these things off or at least expect them to pop up in TypeScript with your your TypeScript comments, and sometimes you just run into a issue where you need to be able to To use one of these things, and you can just turn that off for that specific line or whatever. And you don't have to turn it off on your entire project because you're running into an issue.
Wes Bos
But try to fix it. Try to fix it first. Also try to yeah. Try to fix it. Yeah.
Wes Bos
There was, like, one that it was a high order function where I needed it to be I forget what the specific one was. I think it was strict function types that I was running into where it literally had to be any Because it was a higher order function, and in that case, I had to turn it off. I asked on Twitter, and a lot of people are like, yeah. You this is a use case where you You do have to skirt it. I'll try to find the exact example, and I'll I'll bring it up on a future episode of syntax. But I think that's it. Anything else to add? No. No. That's it. I think that covers it. So TypeScript strict mode is is a fantastic thing, and, strict up your types. Do it. Do it. Do it. Alright. Cool. Well, we will see you in the next episode. We're gonna be doing another potluck. I know this seems like we've been doing a lot of potlucks here, but, hey, we
Scott Tolinski
We were in the process of doing a lot of things, like taking a vacation care as well as moving, and, we were all over the place. So We got so many good questions, and honestly, I had a hard time even picking them because, everybody's been asking the most fantastic questions. So we'll be doing a pollock on Wednesday, and we will see you there. Peace. Peace.
Scott Tolinski
Head on over to syntax.fm for a Full archive of all of our shows. And don't forget to subscribe in your podcast player or drop a review if you like this show.