DEV Community

Cover image for Intro to TypeScript
Bernie January Jr.
Bernie January Jr.

Posted on • Updated on

Intro to TypeScript

TypeScript(TS) is essentially JavaScript, with sugar on top… a Superset of JavaScript(JS). Because of this, whatever code you’d write in a JS file would be legit in a TS file.

JavaScript was created in just 10 days, by Brendan Eich, an employee of Netscape at the time. Yeah, 10 days.

When JavaScript was built, its intended purpose was to create small snippets of code that can be embedded into a webpage, which still happens of course. Today, in addition to JS embeds, developers and software engineers create full-stack web applications that can be written almost entirely in JavaScript.

The language exponentially outgrew its initial scope, and there are more than a few odd quirks and buggy occurrences that may surprise even an experienced developer. For example:

JavaScript’s equality operator (==)

console.log(“” == 0); // logs >> true // that can’t be right?
Enter fullscreen mode Exit fullscreen mode

JavaScript property access

const square = {width: 5, height: 5};
const sqArea = square.widht * square.height; 
console.log(sqArea) // logs  >> NaN // Ok, I'm not the best speller. NaN, really? Shouldn't this log an error?

Enter fullscreen mode Exit fullscreen mode

TypeScript was created to solve these sorts of problems in JavaScript.

Static Type Checking in TS

TypeScript’s core benefit is static type checking, which simply means it will check for an error in your type values without you having to run your code. TS forces JS to act like a statically-typed programming language.

C++ Example: Statically-Typed Programming Languages:
A statically-typed programing language like C++, C# or Java requires different types of variables that explicitly define and store each type of value. A variable that stores an integer in the programming language C++ might look like this:

int num = 10; // declaring a C++ variable as an integer
num = x // NOPE can’t reassign an integer to a string in C++

Enter fullscreen mode Exit fullscreen mode

In this example, the variable num can’t be assigned to a string or any other value that is not a whole number, in fact the number can’t even include a decimal because there’s a different type of variable for floating point numbers called double.

JavaScript Example: A Dynamically-typed Programming Language:
In JavaScript, variables are dynamic and declared at runtime / when the code executes. Variables can also change or be reassigned. As you already know, for example:

let num = 10; // declaring a JS variable
num = x; // OK reassigning a JS variable from a number to a string // JS is 100% ok with this 

Enter fullscreen mode Exit fullscreen mode

Now, let’s run Math.round() on our num.

console.log(Math.round(num) // logs >> NaN // This result is frustrating when you have dozens or hundreds of lines of code in your codebase. You’re now chasing down the value for: num.
Enter fullscreen mode Exit fullscreen mode

Again, TS is trying to solve potential bugs from the code above.

Defining Types in TS

Let’s take advantage of TS static type checking. To do so, we’ll need to define our types explicitly upon declaration like we would in a statically-typed programming language. A demo perhaps… Below is a side-by-side comparison of functions. One written in JavaScript syntax and the same function in TypeScript, where we explicitly define the function’s type arguments.

JavaScript:

function calcArea(radius) {
return 3.14 * radius * radius; // from grade school // π r² 
}
console.log(calcArea(5)); // logs >> 78.5 // that’s what I expected
console.log(calcArea(answer); // log >> NaN // again with this 
Enter fullscreen mode Exit fullscreen mode

TypeScript:

function calcArea(radius: number): number {
return 3.14 * radius * radius; // from grade school // π r² 
}
console.log(calcArea(5)); // logs >> 78.5 // again, expected
console.log(calcArea(answer); // logs >> Error message // now that’s more like it 

Enter fullscreen mode Exit fullscreen mode

In TypeScript, you can declare any variable types that you could declare in JavaScript, and bonus, there are a few additional variable types.

Types in Javascript:
number, string, boolean, null, undefined, object
Typescript includes the above and adds:
any, unknown, never, enum, tuple

Examples of TS with Type Variables

let numeric: number = 123_456_789; // type of number
let words: string = 'Typescript'; // type of string
let blog_published: boolean = true; // type of boolean
let stringsArray: string[] = []; // type of array with strings
let person: [number, string] = [1, 'bernie'] // type of tuple // array with 2 values / flaw with push method
let anything; // type any // can be any type // should rarely be used
function calcTax(income: number){ // function with type of number arguments
return income + 100;
}

Enter fullscreen mode Exit fullscreen mode

In VSCode, you can simply hover on a TS variable or TS function invocation and see what type value is expected before running the function. The Typescript compiler catches these type errors before runtime.

Typescript catches errors before runtime

In Conclusion

Structure Made for Teams

While on the surface, it may seem like it will take more time writing your code in TS versus JS. Let’s imagine the likely scenario where you’re working with a team of developers on a project. Working on a JavaScript project with a team can sometimes feel like hosting a party where every guest speaks a different language.

And what if you’re working in a codebase you’re unfamiliar with and/or a large codebase, in addition to working with a team... This is a situation ripe for miscommunication and misunderstandings i.e. less effective use of time and more collective time debugging.

With TS type definitions and clear interfaces, TypeScript comes to the party keeping everything nice and tidy AND takes on the role of universal translator. TypeScript helps structure your codebase with known values thereby making it easier to maintain.

Resources:

  • TypeScript Docs: The best resource usually lies within the core documentation. The TypeScript docs are organized in a way that both beginners and experienced developers can find what they're looking for. Here is a link to the TypeScript Documentation.
  • TS Setup in less than 10mins | I’d highly recommend watching Alex Ziskind’s YouTube video called TypeScript Set-up in VSCode. He does a really good job of taking things step-by-step in less than 10mins.
  • TS Deep Dive in about 1 hour | The Programming with Mosh channel from software engineer Mosh Hamedani rarely misses, and Mosh does a great job of explaining TypeScript from nuts to bolts in this 1 hour tutorial: TypeScript in 1 Hour.

I hope this was helpful. Happy coding!

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted