4

TypeScript Fundamentals - Vue.js Tutorials

 2 years ago
source link: https://vueschool.io/articles/news/typescript-fundamentals/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

TypeScript Fundamentals

Written by Daniel Kelly

For the past few years TypeScript has been gaining a commanding foothold in the JavaScript world. This is due to the type safety it brings to the JavaScript language. TypeScript leads to safer and more predictable codebases with applications of scale, as well as improves the developer experience through expanded IDE capabilities like smarter auto-complete and error detection.

There's a lot to love about TypeScript but there are many developers who simply haven't taken the plunge yet. If you've been considering doing just that, then now is definitely the time!

Why learn TypeScript now?

  1. The latest version of Vue 3 is written in TypeScript
  2. It's a technology growing in popularity and use
  3. It has some obvious advantages especially for large JavaScript projects
  4. and lastly Vue School has just released an awesome new TypeScript Fundamentals course to get you started!

Check out the introductory lesson now for free and read on to get a preview of some of the other cool things you can learn from the course!

Ok, does learning the fundamentals of TypeScript sound exciting? Of course it does! So here's a rundown on some of the material you can expect to learn.

Static Typing

At the core of TypeScript is the concept of static typing. It's what makes the language so powerful. But what is it? Perhaps the best way to understand static typing is to first understand how normal JavaScript works. In regular ol' JS, we can create a variable and give it a value that is of the type number.

let price = 24 //number

Then anytime during the course of the program we can alter that variable to be any other type.

let price = 24 //number

// ooh that could cause issues
price = "24" //string

// that could be even worse!
price = null //null

// what??
price = "2 goats and a pidgeon" //string

In TypeScript though, none of these shenanigans would be possible.

screenshot of typescript errors

Implicit and Explicit Types

In the example above TypeScript has implicitly (or automatically) set the type of price to be a number and thus price can never be anything besides a number. Besides implicit types, we can also declare explicit types with a special TypeScript syntax. It looks like this.

let price: number = 24

This is useful not only for variable declarations but functions as well.

function sum(x: number, y: number): number{
    return x + y
}

Notice how we can describe what type each parameter (x and y) are, and even the type that the function returns.

Union Types

Simple types like this are excellent and cover a great number of use cases, however sometimes being a little more flexible with the types of our variables, function parameters, and function returns can be useful. That's where union types come in. They allow us to explicitly state that something can legitimately be more than one type.

let booleanOrString: boolean | string = 'I could change'
// TypeScript is ok with this
booleanOrString = true

Literal Types

Another type of type in TypeScript (can I say that... I think I will) is literal types. With literal types we can define variables not just as general types, like string or number, but we can define their type as a literal value.

let pi: 3.14 = 3.14

Notice the 3.14 after the colon. This is the literal type. It's restricting TypeScript to only ever let pi be 3.14 which makes since and we assign it as such after the equals sign.

However this can be done more easily and more clearly without literal types with a good ol' const.

const pi = 3.14

One of the most powerful uses of literals though, come in when combined with union types.

function setProductSize(size: 'small' | 'medium' | 'large' ){
    //...
}

In the setProductSize function, we've used the literal types small, medium, and large to limit the possibilities for what the size parameter will accept. Ooh, now that' interesting!

Interfaces

Furthermore, TypeScript allows us to move beyond describing basic data types by using interfaces to describe objects and/or classes. With interfaces we can define the shape of our objects so that developers and their IDEs can know exactly what properties and methods said objects must, might, and shouldn't contain.

interface Product {
    name: string,
    price: number,
        color?: string, // ? makes optional
    buy(): void // method that must return nothing
}

// if tshirt didn't have a name, price, and buy method
// then TypeScript would mark it as an error
const tshirt: Product = {
    name: 'T-Shirt Design A',
    price: 12,
    color: 'blue',
    buy:()=>{
        console.log('bought!')
    }
}

As you might expect, working with interfaces can be a game changer for the scalability of your enterprise level projects and/or the visibility into the API of your open source projects.

And more!

If any of these topics have piqued your interest, let me tell you this only scratches the surface of TypeScript Fundamentals! All of these concepts and more are explained in greater detail within the course, so you don't want to miss this! If you're ready to start leveling up your career with TypeScript sign up for a Vue School subscription today 💪


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK