Hello, and welcome to another episode of The Bike Shed, a weekly podcast from your friends at ThoughtBot about developing great software. I'm Joel Kinville, and today I'm joined by fellow ThoughtBotter, Jimmy Thinkpin. Hey, Joel. And together, we're here to share a bit of what we've learned along the way. So, Jimmy, what's new in your world? Well, you know, I've been looking at electric bikes and skateboards, actually. I'm trying to figure out how to...
Get around Boulder, Colorado, where I live, without having to jump in my car every time. So that's kind of a fun experience. And then there's a very deep rabbit hole of options. So still not sure what exactly I'll end up with, but fun to research. The gap between bike and skateboard seems pretty big. Right? Yeah, I'm leaning towards a bike more than a skateboard, even though the skateboard does kind of sound cooler. Is this mostly like getting around town sort of thing, like a local commuting vehicle? It's kind of like after the workday, I want to run to the climbing gym.
run by Trader Joe's and Boulder where I am. It's a few miles away. So doable on a skateboard, but safer and probably less exhausting body-wise on a bike. Yeah. How about you, Joel? I've recently been trying to explore a little bit the world of RSS again, trying to bring back what's good with a lot of blogs and newsletters. Right now, I sort of use my email inbox as a sort of pseudo feed reader because most of these places now offer an email newsletter version.
But I'm getting a little bit annoyed with that. And I want to try out more of a classic newsreader experience. This is like back in the pre-Twitter slash X days, right? That was the fad was RSS feeds. Right. I think the one that people loved was Google Reader. That's right. I still hear people occasionally complain about Google killing that project. I think Thoughtbot actually had an RSS feed too for our blog. And we may still have it. We still do. RSS is still alive as a technology. People still use it to pull in things.
Sometimes it can be a little bit more mechanical in that it's less individuals and it might be other places that aggregate content that pull from that. But yeah, RSS feeds are, they're alive. I don't know if I want to say well, but they're a world that I want to dip my toe back into. Yeah, that sounds interesting. I'm excited to hear what comes from that. So I'm excited to have you on the show because I've recently started working on a project that is written in TypeScript.
And TypeScript is not a language I'm very familiar with. That's a slightly different approach to types. I've done a lot of typing in Elm, though. And so the concept of types is a thing that I really like. But seeing it applied in the TypeScript world has been a little bit different. And you've done a lot of running projects. You're pretty familiar with TypeScript. And I'm curious a little bit about you for your experience. What was it like to get into TypeScript for the first time? Well, yeah. So when I started programming back in 2015, that was just a plain JavaScript world. Kind of felt like the Wild Wild West. And I think...
My first TypeScript project was sometime shortly after that, maybe 2016, 2017, when we started playing with it and Microsoft started promoting it. Yeah, I think when I first started using it, it was very confusing, especially coming into the programming world, primarily with JavaScript, which was so loosely typed. So now I've got my linter and everything complaining at me when I don't define a type that can't be inferred. And it was very frustrating. And looking at external libraries that folks that had really understood already, I felt intimidated in the beginning. So there was a learning curve. But at this point...
It feels very helpful, and it's kind of scary to work with just plain JS. Scary in the sense that I feel naked. Yeah, I'm curious how Elm compares. It seems almost type-driven. I've never really used Elm, so. Yeah, Elm is interesting, and I think the biggest thing that hits me up front is the quality of the error messages. Elm is, one of its claims to fame is just how helpful and friendly the error messages are.
whereas TypeScripts very much feel like reading output from a compiler. It's arcane. It's deeply nested. It's complicated. I struggle to read some of those error messages. Oh, yeah. I've heard of people using even like AI to explain TypeScript errors. Definitely have done that on my end. Does it work? Sometimes. Sometimes it just makes you even more confused. Recently, though, I did find a VS Code extension called, I think it's like better TypeScript errors.
It sort of formats them in a less machine, more human-friendly way. So I found that helpful for kind of parsing it with my own brain. But I agree, sometimes the errors... aren't super helpful. And this is the case where sometimes you end up using any on a type and you're just like, I don't know what this thing is. This is very confusing. I'll come back to this. You mentioned any. Another thing that I found really interesting, the difference between Elm and TypeScript is that Elm does not allow you to do any sort of type casting. Whereas TypeScript does. You can tell the compiler, hey, trust me, this value is of this type. I know you don't think it is, but I'm going to override you and tell you that it is this type. Yeah, sort of like a trust me, bro.
Yeah, it is a trust me bro sort of moment. which is oftentimes a nice escape hatch, but also can maybe undermine confidence in the type system as a sort of a backstop for testing all your edge cases. Definitely. It's sort of a cop-out. I only use it whenever I have sort of given up on trying to figure out a type. It's kind of like I've exhausted all options, so I'll use this thing very rarely. But that's interesting in Elm that you just can't. You don't have the option. So I'm curious how you handle those situations where you can't figure out something or you're stumped. Is that something that you often run into with Elm? I think the types tend to be a little bit simpler.
than Web TypeScript offers. And so you don't tend to get stuck in some of these really weird cases. Also, Elm is all about conversions, transforming a value into another. It is a functional language. It will make you, if you want to move from, let's say, a broader type to a narrower type, do type narrowing. TypeScript can automatically infer some of that if you have type guards or you're doing an if-else or something like that. Or you can manually cast it. I think they call it downcasting, where you've got a value that's of a broader type and you're saying, hey, at this point in the program TypeScript, it is now of a narrower type. It won't let you do that. You have to literally transform a value from a broader type to a narrower type. Interesting. Yeah, this makes me think of a lot of things like unions, discriminated unions.
which I think there's a similar thing in Elm, right? And then type narrowing, which in JavaScript or TypeScript, you would use like an if statement oftentimes. And then the TypeScript compiler is smart enough to know, hey, you've narrowed this thing with your if statement using the discriminator. Now I know that only these properties exist. So that's pretty cool, a cool feature of TypeScript. It sounds like Elm is almost more tedious for narrowing types. It can be. It doesn't do some of these things automatically for you. But at the same time, it's a little bit more robust in terms of absolutely making sure that all those edge cases are taken care of. Yeah.
Elm doesn't have as much of the concept of supertypes and subtypes. And so in TypeScript, you can have a value that is, let's say it's nullable. So you have a string or null. It's a union of those two. But then you can have an if-else statement we check. If the value is null, go one branch, else go another branch. And TypeScript can be smart enough where once you're in that else branch, it knows that your value is now not null. It's a string. And it's not going to force you to do more presence checks along. You don't need to have that safe navigation or anything like that.
because it has narrowed that type down. Elm doesn't do unions the way that TypeScript does, where it will say a value is either a string or it's a null value. Instead, it just has a regular string type, and there's a nullable wrapper that you put around it. Oh, okay. They call it the maybe type. But if you've done, let's say Swift, they have an optional type. A lot of languages will do either maybe or option as this value. Okay. And so...
Anytime you have this optional type, the compiler will force you to effectively unwrap it before you access the value inside because the value inside is potentially not present. But after you have unwrapped it, then you have access to it and it's no longer considered nullable. And so the equivalent to that typeguard scenario is that Elm, you would have a, let's say, a maybe string. You would have a case expression on it where you're attempting to unwrap it. You have a branch for if it's present, a branch for if it's not present.
And then inside the branch where it's present, then you have access to the unwrapped string. And the Elm compiler, as long as you're referencing the unwrapped string in that branch, is happy to let you do things with it because it is now no longer nullable. If you end up with similar code, it's just a different mechanism. Yeah, it's not similar. I think that what the difference is, I'm realizing, is Elm does not do unions the way TypeScript does. All of its combining of different types is done with something closer to a discriminated union. Gotcha. So you can't have a value that's either a string or an integer. Instead, what you have is sort of two wrappers.
Or you have sort of a unified wrapper that has two variants, either a string variant or an integer variant. And the compiler is going to force you to branch on those two before you can access the value inside. Yeah, similar in TypeScript where you have the discriminator, the key that's common between the two in your union. Exactly. So coming back a little bit to your experience, there's a lot of concepts to pick up on. Oh, yeah. I'm curious if for you, there were some moments that were sort of big breakthroughs or concepts that once you figured out all of a sudden were like light bulb moments that really let you sort of jump forward in your TypeScript knowledge. Yeah, I think understanding type inference was like, whoa, this is really powerful. When I realized TypeScript just knows a lot of things and I don't have to explicitly define types. I think in the beginning, I was just like, oh, I'm using TypeScript. So this thing, I'll just say it's a string, even though, you know, I'm like saying const name equals string or equals Jimmy.
I would say like const name colon string equals Jimmy, which isn't necessary for TypeScript because it's smart enough to say, oh, okay, you've defined this variable as a string. I know it's a string. It will always be a string. And also TypeScript can do that with functions and like return types. It will look at your logic after your return and be like, okay, if you're returning a string, you know, I'll say I'll infer this as a string or maybe you're returning a Boolean. It'll work for that. So I thought, I think that's really powerful. And I, it was like an aha moment of, okay, I need to trust the system and let it work for me. And then define the types when the errors start popping up. I think another.
thing I didn't quite understand was the configuration. TypeScript can be pretty confusing when you're first jumping into it. you have this tsconfig file and you're like, I don't know what any of these options are. Is this useful? There is one really useful option that's like the enable strict mode flag. And that does a lot of things with like kind of tightening up the system and the type checks where it won't let n plus and any's just litter your code base. It will make you define things if the compiler can't for the type. And it will also help you with undefined values and ensure that you do like optional chaining when something might be undefined. Does it also enable null checking or is that a separate thing that has to be turned on? I think that's part of the enable strict mode option. There's like a strict null checks flag that.
defaults to true. Checks for null and undefined. This is one confusing part of JavaScript. Null versus undefined. I think one of the things that really impressed me when I first got into type systems with Elm was the fact that it was able to find all the edge cases where I had potentially data that was not present.
nullable values and correctly make me do presence checks for all of them. And coming from Ruby, where we play a lot more fast and loose with data, there's a lot of things that I'd never really thought of as potentially being dangerous. So for example, accessing the first element of an array. But there's always the case of, but what if the array is empty? Did you think about that edge case? And the answer is oftentimes no. And then I end up with a null error that blows up in production. And so having that safety and knowing that the type system can sort of help you discover the edge cases that you didn't
think about for yourself. And then leaning on it as a tool to help sort of discover edge cases was a big mindset shift for me. Yeah, totally. TypeScript was very helpful when it comes to like things that would be undefined that you wouldn't otherwise catch until you try to render code and something crashes. And then it's kind of a hunt to figure out exactly what's happening. Definitely helps cut down on those sort of situations. I'm now at the point where on this TypeScript project that I'm running, if I encounter a bug in the browser while I'm like testing a local feature.
And I realize, oh, this is like a nullability bug or something like that. I get really annoyed because I'm asking myself, why didn't the compiler catch this? This feels like the kind of thing that I shouldn't have gotten lucky and stumbled across it while QAing. This is something that should have been in my face by the type checker. And usually the way that happens is because we have overridden the type checker and cast a value, say it's going to be in the shape, I promise. Yeah, trust me, bro. This object will have these keys. And this is oftentimes external data.
So maybe data from an API or data that we're reading from, let's say, the URL params. And sometimes we expect certain keys to be present and they're not present. And then the program blows up. Yeah, that's like runtime checking, which TypeScript doesn't really do out of the box. You're kind of talking about, right? Versus the compile time. Yes and no. And this, I think, is where there's a terminology difference. Because I think if you were to do some parsing or transformation at the boundaries of your system.
It sounds like the TypeScript community refers to this as runtime checking. But this is not information that is unknowable at compile time. The information is knowable at compile time. It's just that some of the actual work of transforming it happens at runtime. And this information is knowable at compile time, and you can have safety around it.
I think what you have to accept, though, is that the type that's coming in from, let's say, reading the URL parameters, it's not going to be an object in the particular shape that you tell it. What you really have is any object. An object with, maybe you can say it's an object with string keys because that's what the browser gives you, but you don't know what keys are going to be in it and what the keys point to is going to be arbitrary. Or maybe it's strings to strings. Maybe that's the most you can know with certainty. Yeah. So this is kind of like, how do you trust that external API you were using to be consistent? How do you build in checks?
So that's where you're doing type narrowing. But if you tell TypeScript, hey, use this narrower type, and you don't provide what to do for values that fall outside of that, that are in the broader type, but that don't fit into your narrower type, that's when you're going to have bugs. And so this sort of runtime checking thing that you're talking about is effectively converting that broad type into the narrow type. And if that conversion function has a type signature on it that goes from the broad type, let's say record string string to some custom thing that you have, then you have type safety statically at compile time all the way from that sort of very amorphous data through your system. So I tend to think of that as compile time safety, but I think the TypeScript community seems to talk about this using the language of runtime checking. Yeah, maybe it's how the errors are presented to the end user and the extra checks and how they would like throw an error with that additional safety net instead of your app just crashing.
your user might get a nice error if you're doing this narrowing and checking. There's all sorts of things that you could do. The thing is that you're being honest to TypeScript about what the inputs are. So you're being honest to TypeScript and saying, the input is going to be this broader type. I want it to get to here, and then here's a conversion function. That conversion function can just be, let's say, plugging in a bunch of defaults. So let's say you're trying to read a bunch of, you want an object with certain keys in it, but you have a default for all the keys where it's not present.
So you say, read the keys of the present in the URL for AMs. Use those. Otherwise, use my default. Then there's no error to show or anything. It just is a sort of a clean transformation. That's a nice way to handle it, yeah. And you don't always have that. Sometimes you have potential errors. And like you said, you have more control over the errors. The errors also happen closer to the edges of your system. Yes. And so you don't get some unexpected null or undefined deep in your program that you have to track down. Yeah. You can have a more specific error in some cases where it's more useful to the end user versus just there is an app error. More useful to the end user.
And also easier for you, the developer, to debug because it's happening closer to the source, where it surfaces closer to the source. Exactly. Yeah. I have this sort of mental model for the idea of parsing. where I think previously I thought of parsing as you turn strings into some richer data type. And now my mental model is a little bit more of a, you take as input a broad type and your output of this function is a narrower type. So it's a kind of type narrowing, but it's going from broad to narrow with potential error throwing because not all values in the broad type can be successfully converted to the narrow type. Interesting. Have you worked on something recently where this has been a thing you've had to figure out?
maybe hit this end edge case where this value isn't something you expected? So I think that any sort of API ingestion is going to be something like this. And there's almost sort of a few different passes you could do, which you get back from the server when you make an API request is going to be a string in the body. Strings are a very, very broad type. And maybe the server tells you, hey, this string I'm sending you is in JSON format. But strings are a broader...
type than JSON. Not all strings contain valid JSON. So you try to turn that string into JSON, and not all values are going to fit. So that's already going from a broad type to a slightly narrower one. But maybe it did fit. So now you've parsed it, potentially had an error JSON parse error. Maybe you successfully parsed. Now you're in a narrower type, but you're still in the type of all possible JSON values. And that's incredibly broad. And JSON doesn't even have to just be objects, right? A raw number is valid JSON. A Boolean is valid JSON. An array is valid JSON.
So if you were expecting an object with certain keys, well, good luck. All sorts of other things might happen that might blow up your system. And so then there's the type of all valid JSONs to your particular object shape. And that's another pretty significant narrowing that has to happen. Yeah, this makes me think of how we've used Zod on a recent project a lot more than I have on other projects to validate what we're talking about is strings from an external API and then ensuring that, hey, this thing actually does have these keys in the payload and it matches the shape we expect. And if it doesn't, then we can throw an error closer to the edge like you've been mentioning.
So I'm really curious about Zod. Would that be a form of what you were referring to as runtime checking? Is that what you called it? That's what I called it. Yeah, that's...
that's kind of what we what we've been using to validate payloads like i was saying um and includes methods that help you like parse that random string from api in a safe way i think it might even be called safe parse and then after you do that sort of thing you can run the payload through azot object schema which will check ensure the types match and then after that you know yay we're good to go we can use this thing in our logic so that's sort of that runtime check which in previous projects we didn't really have as robust of checking you know it might be like an if an if statement where we're just kind of ensuring keys exist but it's not as easily just like kind of plug and play as Zod. Yeah, you said you're on a TypeScript project. Are y'all using Zod or something else? We are not, but I'm advocating that we bring it in. So I've not used it. I know that we need some sort of parse or transformation thing to happen at the edges so that we have that safety from TypeScript, so that we're no longer lying to TypeScript and telling it to trust us. And Zod seems to be the more or less community-favored library that does this, but I've yet to try it myself. So I was very curious about your experience with it. Does it feel tedious? Does it feel useful?
Definitely useful and not just for this sort of case. We're also using a package called React hook form and Zod we're using for the schemas, like the form schemas and validating, hey, the user put in a string in this number field or the length is what we want or that, hey, this is a valid phone number. We can also create utilities where we plug them into that Zod schema. You know, maybe some rejects to validate like a zip code. So yeah, I think it was a little bit of a learning curve. You know, there is another library. You've got to learn the syntax and some of the methods, but it was decently intuitive. And Zod has like a Zod playground online that you can go to and kind of poke around and mess with things.
I think the role that Zod fills is very similar to in the Elm world. There's a first party library that comes with a language called JSON decoders. And it's similar to that. It takes this sort of, as its input, the sort of broad type of all valid JSON values. So sort of amorphous, it could be almost anything. And then you can transform that into something of the shape you want by saying, I expect this value of this key to be present. And then I'm going to pull it out and build my own sort of object in the shape that I need to. So it's not just validation. It's actually transformation. Okay.
but it doesn't enforce a schema on the JSON. And the compiler then knows how to, if you're doing that parsing, it knows that that's an operation that will potentially fail. And so it will force you to handle that failure. Interesting. Yeah, this makes me think of Zod and it actually can transform as well. Like you could transform a string value from an API response to a number with that Zod runtime validation we were discussing. And then right there, when you're working with your payload, you don't have to do that yourself. You can just trust Zod to do it for you. There's an article that I've mentioned on the show before that has been very influential for me. It's called Parse Don't Validate. And it's written for Haskell programmers. But the general idea is that ideally, when you're going from these sort of broad types where there's a lot of uncertainty, don't just like...
write a check that says, oh, is this value nullable or not? And then pass that same value down the line and just tell somebody else, trust me, I checked it. Instead, do some sort of transformation of that object into a shape where it's sort of guaranteed to be present, that the type checker can guarantee for you. And then everybody else downstream has that sort of guaranteed built in. So by doing transformation rather than simple validation, you can say, well, before this, the values are of a type that's nullable. After this, they are of a non-nullable type. And maybe it's an object with slightly different keys or something like that. Yeah, so that sounds similar to Zod, but yeah, more about transforming it into an entirely new object, which maybe it's easier to follow in the code. Yeah, I'm curious if you can do something similar in Zod. It sounds very similar to mine.
my brain. That's sort of the way that I'm approaching it. It's like, oh, Zod is like TypeScript's JSON decoder library. Okay, yeah. I was like, how is this different than Zod? It sounds similar, but different.
I'm curious, based on your experience, what would be some sort of best practices that you'd recommend for people writing TypeScript? Or maybe even some like pitfalls to avoid as someone who's newer to the language and type system and trying to get used to it? Good question. I think, you know, if you're just getting into TypeScript, curious about these best practices, using that enable strict mode flag in your TS config can definitely be helpful. And it'll really show you kind of the strength of TypeScript more so than just inferring innies and not having as much type safety in your app. And then...
Like I was mentioning at the beginning of the podcast, unnecessary type annotations. So that kind of means trust TypeScript to infer things when it can, and then add types as needed. So don't just start defining types for every single thing because that's unnecessary. It can make code harder to read for other folks that you're working with. So I think trusting the inference and letting it do its thing is helpful and results in less code, easier to read, and you're just defining the types where they're necessary. TypeScript also has a bunch of really helpful utility types. So there's one called partial, which is a K.
i'm just pulling you know this value from this type from this object this is all i want right now this is what's required there's omit which is you know exclude this value from this type and then there is pick which is hey i just want this specific key like from this type partialist reminds me of any it's kind of loose so i try to use that more sparingly but i found that those utilities types helpful yeah and then there's also you know type guards and narrowing types which at first i was very confused by that and ran into cases where say i have like a react component that's for a form and this form is for new entries and editing entries. I got really mixed up at one point trying to define the data schema for that form because sometimes there would be an ID and sometimes there wouldn't be. And this is kind of what made me have an aha moment with type narrowing and guards and letting it understand, okay, I'm cool with this if the ID is there. Otherwise, I know that it's the new form. It's almost like a forcing of Schrodinger's box. What's that?
A quantum thought experiment. The cat is alive and dead until you open the box. I've never heard of this. Oh, it's a famous thought experiment to explain the idea of superpositions in quantum physics. Where everything can be kind of like both states. Right, right. You'd have a zero and or one at the same time. Exactly. Until they are observed. And then at the point of observation, it sort of collapses down to one state. Yeah, because at some point it has to, yeah. For some parts of your code, the form is sort of both new and edit versions.
until you sort of do a check on that ID. And then now within that branch, you are guaranteed to only be the new form or guaranteed to only be the update form. Ah, yeah, I see the resemblance. Yes. Yeah, well, I'm curious, Dwell, what have you found most helpful coming into TypeScript? Was there anything that you found really helpful over other things?
I like the editor tooling. The editor integration is great. The language server is great. For someone who doesn't know the language that much, having that editor tooling has really helped me ramp up pretty fast. I love being able to just sort of see anywhere in the editor, oh, this type all of a sudden doesn't work well. I made a change here, but it broke something over there. So I really appreciated that. That's helped me ramp up fast. Yeah, the autocomplete IntelliSense with VS Code is really awesome. And you can command click a type and see the definition really fast. I found it really helpful with refactoring as well. Yes, for sure.
I'm curious, as you mentioned earlier on, about readability and types. And you mentioned that avoiding adding... too many types because that impacts readability, I think is the recommendation that you made. To what extent do you feel like types increase readability? And in what situations do you feel like they detract from it? That's a good question, because I think in a sense, it does help with readability. If I'm jumping into a code base and there are types defined, you know, maybe for an API request, it's helpful to see, okay, like this is the response shape I might get back and the types of those keys. I think it can be sort of unhelpful if there are unnecessary types, you know, folks that are kind of on the, hey, I'm a pure JavaScript.
This is all I do. I hate TypeScript. I don't know if there are actually that many sort of people around, but they would maybe say TypeScript, it's just kind of jumping up your JavaScript. It's adding all of the syntax. This is harder for me to read. You know, there are two sides where it can be helpful, but if there are unnecessary type annotations, it can be kind of confusing, especially for a beginner because then they might not know what TypeScript can do out of the box with type inference. And that just kind of comes with working with TypeScript. You slowly understand what can be inferred, what can't, where do I need to start defining types maybe to start like type first programming and where can I just like trust the system to kind of do this for me.
On the show, we're a huge fan of the idea of heuristics. I'm curious, do you have a sort of personal heuristic that you use on when to add a type and when not? Sort of a guideline for, yeah, you know, in these sorts of conditions or this general shape of problem, I like to use a type and this shape of problem, I tend to not use a type. That's a good question. Or maybe you're a full-on minimalist. The fewest amount of types that TypeScript will let you get away with.
I mean, it really is where it's kind of sugar on top of JavaScript, where you don't really have to define that many types. With enable strict set to true, you'll eventually run to a case where it's like, hey, I don't know what this thing is. It's in any value. You need to be more specific. So I'm sort of the type of developer that maybe, yeah, more minimalistic approach where I'll add TypeScript as I'm kind of working as ESLint and the system are telling me, hey, you need to be more specific here to find your types. I recently did implement authentication on a project, and I started kind of that build with defining a user type and the keys I would expect on the user.
So that was kind of helpful, like a mental model to start with. Okay, I'm going to have this user I need, you know, first name, last name, then number zip. And then I can kind of plug that in where I'm going to be using the user throughout the application, maybe an API response and some forms. So, yeah. It's almost more of a type-driven approach.
Definitely in that case, yeah. But for those getting started with TypeScript, I love the recommendation of saying, turn on that strict mode and then just let the compiler tell you where you need types and follow that. And then that's good enough for your getting started with TypeScript. And then you can get fancier along the way. You can then, instead of having maybe the type checker lag behind you, you do work and then it tells you all these things. You can then sort of have it be ahead of you, like you were saying, a more type-driven approach where you start with the types and then let it help you figure out the implementation. Totally. And have that ESLint extension, I think, which is the main one for TypeScript with VS Code.
if you're in the VS Code world. Well, on that note, let's wrap up. Jimmy, thank you so much for joining on the show and sharing your thoughts and expertise and experience on TypeScript. Yeah, thanks, y'all. That was fun. Let's do it again sometime.