DEV Community

Brad Hankee
Brad Hankee

Posted on

TypeScript Primer ( Intro -> Kinda Advanced)

Why TypeScript? I mean do we really want to write more code when the whole talk over the last decade has been about being more concise.
YES!
Yes, because writing a little more up front will help prevent all those production bugs that no one can afford. This can prevent you or others from drilling down call stacks in the browser dev tools as well.

Another, and maybe the best reason, is the integrated documentation and IntelliSense that will make your life as a developer great since it feels like your coding with a rubber duck always looking over your shoulder screaming in your ear what you can and cannot do.

Alt Text

How does TypeScript work?
TypeScript is written in .ts extension files. This allows the typescript compiler, which the user installs, to see these files and compile them into the vanilla JS files.

TypeScript Basics

Type Inference(Implicit)- Typescript guesses the type for us

let firstTS = 36
// This will show as: let firstTS: number

Enter fullscreen mode Exit fullscreen mode

Type Annotations(Explicit) - We (devs) tell TypeScript the type

let firstTSAgain: number = 36
// This will show as: let firstTS: number

Enter fullscreen mode Exit fullscreen mode

As you can see both have same result as TypeScript will apply type number when variable is declared with a value as number. In this case there's no need to specify and be redundant. But if you are declaring a variable with out a value this is necessary.

let missingVal: number

// You can also extend to have multiple types such as:
let moreOptions: (number | string)

Enter fullscreen mode Exit fullscreen mode

Types and Interfaces

One of the best parts of TypeScript is creating your own types which really allows you to control the structure of your code to a precise level. In this example we're making a type that can only be a certain string in a set of strings that we specify.

type FavBand = "Weezer" | "Tool" | "GreenDay" | "Dropkick Murphys"

let coolBand: FavBand = "Tool"
Enter fullscreen mode Exit fullscreen mode

Interfaces are very much like types but more specific to data shapes such as objects like we see here. Notice in the property for drinksCoffee the ?. This is to set this property to be optional and not mandatory.

interface PathToSenJSDev {
    language: string,
    drinksCoffee?: boolean
}

let dev: PathToSenJSDev = { 
    language: 'JS',   
    drinksCoffee: true   
}
Enter fullscreen mode Exit fullscreen mode

Functions

A basic version of a function is shown here where the parameters are set as a type and then after the parentheses the return value of the function is also specified. If a string were to be passed in the function call TypeScript would show an error on the spot.


function doubleMe(num: number): number {
    return num * 2
}

doubleMe(2)
Enter fullscreen mode Exit fullscreen mode

Mapped Types

My favorite part of TypeScript so far. Think of mapped types as being able to apply specific functionality over another type.

In this example we're going to use food to learn about mapped types by setting a recipe interface and then learning how to map over the interface and make the properties readonly and optional.


type range = 1|2|3|4|5|6|7|8|9|10

// Main Interface
 interface Recipe {
     numIngred: number;
     cookMethod: string;
     score: range
 }

 let BeefBourguignon: Recipe = {
    numIngred: 8,
    cookMethod: "Simmer",
    score: 9
 }

// Here we can modify 
 BeefBourguignon.numIngred = 2;


// Create a readonly version that can map over a type 
// Syntax [P in keyof T] is depicting "Property in keyof Type"

 type ReadOnlyRecipe<T> = {
     readonly [P in keyof T]: T[P]
 }

 let readOnlyBeefBourguignon: ReadOnlyRecipe<Recipe> = {
    numIngred: 8,
    cookMethod: "Simmer",
    score: 9
 }
// Will not allow since this is now readonly
//  readOnlyBeefBourguignon.numIngred = 4


//Different version for adding optional to each property
 type OptionalProps<T> = {
     [P in keyof T]? : T[P]
 }
Enter fullscreen mode Exit fullscreen mode

Wrap Up

This is just a primer that includes a small small set of features for TypeScript but I hope I picked some good use cases where it would be easy to see how simple it is to start using as well as the power of the extendability it can have on a codebase. I think it is safe to say if you are planning on being a JavaScript dev at least for the next few years you should have this in your toolset.

-- Brad
PathToSeniorJS

Top comments (1)

Collapse
 
gixxerblade profile image
Steve Clark πŸ€·β€β™€οΈ • Edited

enum, type, interface
headache