Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m
Lessons:14Length:1.2 hours
Typescript fundamentals 400x277
  • Overview
  • Transcript

3.1 6 Dos and Don'ts in TypeScript

Hi, and welcome back to TypeScript Fundamentals. For this lesson, I've picked six things that are done differently in TypeScript compared to regular JavaScript. In the worst case, those differences can lead to bugs or unexpected behavior that are hard to find when debugging. Let's start with a very basic don't. This is very common. If you remember the lesson about variable declaration, I talked about basic types like numbers, strings, booleans, and objects. There are similar types in JavaScript. They look almost the same. The only difference is an uppercase letter at the beginning. But they aren't real types in TypeScript terms, but rather, box objects. Using them can result in unexpected and unwanted behavior. So don't use Number, String, Boolean, or Object, always use the lowercase equivalence for type definition. The next one is about function ordering. With TypeScript, it is possible to do function overloading. So you can have functions with the same name, taking different parameters and returning different types. It's important that you always sort the function declarations, so that the more specific ones come first. And the most general ones are last. This is important, because TypeScript will always choose the first mentioned overload to be executed. And speaking of overloading, don't misuse it. If you have overloads that only differ in the trailing parameters, but have the same return type, make them optional instead of multiple different functions. The same goes for overloads that only differ by type in one argument. That's what union types are for. And they can be especially useful if you are just passing an argument through to another function. And finally, callbacks, they are very common in Javascript, as it's a way of asynchronously executing code. If you have a callback that has an optional parameter which you pass in every time, just to give people calling a function the option to avoid it, make it non-optional. It's always okay to provide a callback that accepts fewer arguments. This also makes method overloading unnecessary if the overload only differs in the number of callback parameters. This also avoids mistakes regard the overload order, and allowing malformed callbacks, in defining a margin error callback first. Another common mistake is to use the any key word. If you don't care about the return value of a callback, the solution is simple and should be pretty obvious. You use void instead. Those six language-specific dos and don'ts will help you avoid mistakes in starting out with developing in TypeScript. In the next and final lesson of this course, I'm going to point you to a few resources that might be useful in getting proficient with TypeScript. See you there.

Back to the top