Docsity

Typescript handbook for beginners, Cheat Sheet of Computer Science

Partial preview of the text

Download Typescript handbook for beginners and more Cheat Sheet Computer Science in PDF only on Docsity!

This copy of the TypeScript handbook was

created on Friday, June 24, 2022 against commit

e538f6 with TypeScript 4.7.

Table of Contents

The TypeScript Handbook Your first step to learn TypeScript

The Basics Step one in learning TypeScript: The basic types.

Everyday Types The language primitives.

Narrowing

Understand how TypeScript uses JavaScript knowledge

to reduce the amount of type syntax in your projects.

More on Functions Learn about how Functions work in TypeScript.

Object Types

How TypeScript describes the shapes of JavaScript

objects.

Creating Types from Types An overview of the ways in which you can create more

types from existing types.

Generics Types which take parameters

Keyof Type Operator Using the keyof operator in type contexts.

Typeof Type Operator Using the typeof operator in type contexts.

Indexed Access Types Using Type['a'] syntax to access a subset of a type.

Conditional Types

Create types which act like if statements in the type

system.

Mapped Types Generating types by re-using an existing type.

Template Literal Types Generating mapping types which change properties via

template literal strings.

Classes How classes work in TypeScript

Modules How JavaScript handles communicating across file

boundaries.

A reader who completes the walkthrough should be able to:

Read and understand commonly-used TypeScript syntax and patterns

Explain the effects of important compiler options

Correctly predict type system behavior in most cases

In the interests of clarity and brevity, the main content of the Handbook will not explore every

edge case or minutiae of the features being covered. You can find more details on particular

concepts in the reference articles.

Reference Files

The reference section below the handbook in the navigation is built to provide a richer

understanding of how a particular part of TypeScript works. You can read it top-to-bottom, but

each section aims to provide a deeper explanation of a single concept - meaning there is no aim

for continuity.

Non-Goals

The Handbook is also intended to be a concise document that can be comfortably read in a few

hours. Certain topics won't be covered in order to keep things short.

Specifically, the Handbook does not fully introduce core JavaScript basics like functions, classes, and

closures. Where appropriate, we'll include links to background reading that you can use to read up

on those concepts.

The Handbook also isn't intended to be a replacement for a language specification. In some cases,

edge cases or formal descriptions of behavior will be skipped in favor of high-level, easier-to-

understand explanations. Instead, there are separate reference pages that more precisely and

formally describe many aspects of TypeScript's behavior. The reference pages are not intended for

readers unfamiliar with TypeScript, so they may use advanced terminology or reference topics you

haven't read about yet.

Finally, the Handbook won't cover how TypeScript interacts with other tools, except where

necessary. Topics like how to configure TypeScript with webpack, rollup, parcel, react, babel, closure,

lerna, rush, bazel, preact, vue, angular, svelte, jquery, yarn, or npm are out of scope - you can find

these resources elsewhere on the web.

Get Started

Before getting started with The Basics, we recommend reading one of the following introductory

pages. These introductions are intended to highlight key similarities and differences between

TypeScript and your favored programming language, and clear up common misconceptions

specific to those languages.

TypeScript for New Programmers

TypeScript for JavaScript Programmers

TypeScript for OOP Programmers

TypeScript for Functional Programmers

Otherwise, jump to The Basics or grab a copy in Epub or PDF form.

What about that second line of code? If you're familiar with JavaScript, you'll know this fails with an

exception:

It'd be great if we could avoid mistakes like this.

When we run our code, the way that our JavaScript runtime chooses what to do is by figuring out

thetype of the value - what sorts of behaviors and capabilities it has. That's part of what that

TypeError is alluding to - it's saying that the string "Hello World!" cannot be called as a

function.

For some values, such as the primitives string and number , we can identify their type at runtime

using the typeof operator. But for other things like functions, there's no corresponding runtime

mechanism to identify their types. For example, consider this function:

We canobserve by reading the code that this function will only work if given an object with a

callable flip property, but JavaScript doesn't surface this information in a way that we can check

while the code is running. The only way in pure JavaScript to tell what fn does with a particular

value is to call it and see what happens. This kind of behavior makes it hard to predict what code

will do before it runs, which means it's harder to know what your code is going to do while you're

writing it.

Seen in this way, atype is the concept of describing which values can be passed to fn and which

will crash. JavaScript only truly providesdynamic typing - running the code to see what happens.

The alternative is to use astatic type system to make predictions about what code is expected

before it runs.

Static type-checking

Think back to that TypeError we got earlier from trying to call a string as a function.Most

people don't like to get any sorts of errors when running their code - those are considered bugs!

And when we write new code, we try our best to avoid introducing new bugs.

TypeError: message is not a function

function fn(x) { return x.flip(); }

If we add just a bit of code, save our file, re-run the code, and immediately see the error, we might

be able to isolate the problem quickly; but that's not always the case. We might not have tested the

feature thoroughly enough, so we might never actually run into a potential error that would be

thrown! Or if we were lucky enough to witness the error, we might have ended up doing large

refactorings and adding a lot of different code that we're forced to dig through.

Ideally, we could have a tool that helps us find these bugsbefore our code runs. That's what a static

type-checker like TypeScript does.Static types systems describe the shapes and behaviors of what

our values will be when we run our programs. A type-checker like TypeScript uses that information

and tells us when things might be going off the rails.

Running that last sample with TypeScript will give us an error message before we run the code in

the first place.

Non-exception Failures

So far we've been discussing certain things like runtime errors - cases where the JavaScript runtime

tells us that it thinks something is nonsensical. Those cases come up because the ECMAScript

specification has explicit instructions on how the language should behave when it runs into

something unexpected.

For example, the specification says that trying to call something that isn't callable should throw an

error. Maybe that sounds like "obvious behavior", but you could imagine that accessing a property

that doesn't exist on an object should throw an error too. Instead, JavaScript gives us different

behavior and returns the value undefined :

const message = "hello!";

message();

This expression is not callable. Type 'String' has no call signatures.

This expression is not callable. Type 'String' has no call signatures.

const user = { name: "Daniel", age: 26, };

user.location; // returns undefined

Types for Tooling

TypeScript can catch bugs when we make mistakes in our code. That's great, but TypeScript can

also prevent us from making those mistakes in the first place.

The type-checker has information to check things like whether we're accessing the right properties

on variables and other properties. Once it has that information, it can also startsuggesting which

properties you might want to use.

That means TypeScript can be leveraged for editing code too, and the core type-checker can

provide error messages and code completion as you type in the editor. That's part of what people

often refer to when they talk about tooling in TypeScript.

TypeScript takes tooling seriously, and that goes beyond completions and errors as you type. An

editor that supports TypeScript can deliver "quick fixes" to automatically fix errors, refactorings to

easily re-organize code, and useful navigation features for jumping to definitions of a variable, or

finding all references to a given variable. All of this is built on top of the type-checker and is fully

cross-platform, so it's likely that your favorite editor has TypeScript support available.

const value = Math.random() < 0.5? "a" : "b"; if (value !== "a") { // ... } else if (value === "b") {

This condition will always return 'false' since the types '"a"' and '"b"' have no overlap. // Oops, unreachable }

This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.

import express from "express"; const app = express();

app.get("/", function (req, res) { res.sen

});

app.listen(3000);

send sendDate sendfile sendFile

tsc (^) , the TypeScript compiler

We've been talking about type-checking, but we haven't yet used our type-checker. Let's get

acquainted with our new friend tsc , the TypeScript compiler. First we'll need to grab it via npm.

This installs the TypeScript Compiler tsc globally. You can use npx or similar tools if you'd prefer to run tsc from a local node_modules package instead.

Now let's move to an empty folder and try writing our first TypeScript program: hello.ts :

Notice there are no frills here; this "hello world" program looks identical to what you'd write for a

"hello world" program in JavaScript. And now let's type-check it by running the command tsc

which was installed for us by the typescript package.

Tada!

Wait, "tada"what exactly? We ran tsc and nothing happened! Well, there were no type errors, so

we didn't get any output in our console since there was nothing to report.

But check again - we got somefile output instead. If we look in our current directory, we'll see a

hello.js file next to hello.ts. That's the output from our hello.ts file after tsc compiles

ortransforms it into a plain JavaScript file. And if we check the contents, we'll see what TypeScript

spits out after it processes a .ts file:

npm install -g typescript

// Greets the world. console.log("Hello world!");

tsc hello.ts

// Greets the world. console.log("Hello world!");

noEmitOnError compiler option. Try changing your hello.ts file and running tsc with that

flag:

You'll notice that hello.js never gets updated.

Explicit Types

Up until now, we haven't told TypeScript what person or date are. Let's edit the code to tell

TypeScript that person is a string , and that date should be a Date object. We'll also use the

toDateString() method on date.

What we did was addtype annotations on person and date to describe what types of values

greet can be called with. You can read that signature as " greet takes a person of type

string , and a date of type Date ".

With this, TypeScript can tell us about other cases where greet might have been called incorrectly.

For example...

Huh? TypeScript reported an error on our second argument, but why?

tsc --noEmitOnError hello.ts

function greet(person: string, date: Date) { console.log(Hello ${person}, today is ${date.toDateString()}!); }

function greet(person: string, date: Date) { console.log(Hello ${person}, today is ${date.toDateString()}!); }

greet("Maddison", Date());

Argument of type 'string' is not assignable to parameter of type 'Date'.

Argument of type 'string' is not assignable to parameter of type 'Date'.

Perhaps surprisingly, calling Date() in JavaScript returns a string. On the other hand,

constructing a Date with new Date() actually gives us what we were expecting.

Anyway, we can quickly fix up the error:

Keep in mind, we don't always have to write explicit type annotations. In many cases, TypeScript can

even justinfer (or "figure out") the types for us even if we omit them.

Even though we didn't tell TypeScript that msg had the type string it was able to figure that out.

That's a feature, and it's best not to add annotations when the type system would end up inferring

the same type anyway.

Note: The message bubble inside the previous code sample is what your editor would show if you had hovered over the word.

Erased Types

Let's take a look at what happens when we compile the above function greet with tsc to output

JavaScript:

greet("Maddison", new Date());

function greet(person: string, date: Date) { console.log(Hello ${person}, today is ${date.toDateString()}!); }

let msg = "hello there!";

let msg: string

"use strict"; function greet(person, date) { console.log("Hello ".concat(person, ", today is ").concat(date.toDateS } greet("Maddison", new Date());

While the default target is ES3, the great majority of current browsers support ES2015. Most developers can therefore safely specify ES2015 or above as a target, unless compatibility with certain ancient browsers is important.

Strictness

Different users come to TypeScript looking for different things in a type-checker. Some people are

looking for a more loose opt-in experience which can help validate only some parts of their

program, and still have decent tooling. This is the default experience with TypeScript, where types

are optional, inference takes the most lenient types, and there's no checking for potentially

null / undefined values. Much like how tsc emits in the face of errors, these defaults are put in

place to stay out of your way. If you're migrating existing JavaScript, that might be a desirable first

step.

In contrast, a lot of users prefer to have TypeScript validate as much as it can straight away, and

that's why the language provides strictness settings as well. These strictness settings turn static

type-checking from a switch (either your code is checked or not) into something closer to a dial. The

further you turn this dial up, the more TypeScript will check for you. This can require a little extra

work, but generally speaking it pays for itself in the long run, and enables more thorough checks

and more accurate tooling. When possible, a new codebase should always turn these strictness

checks on.

TypeScript has several type-checking strictness flags that can be turned on or off, and all of our

examples will be written with all of them enabled unless otherwise stated. The strict flag in the

CLI, or "strict": true in a tsconfig.json toggles them all on simultaneously, but we can

opt out of them individually. The two biggest ones you should know about are noImplicitAny

and strictNullChecks.

noImplicitAny

Recall that in some places, TypeScript doesn't try to infer types for us and instead falls back to the

most lenient type: any. This isn't the worst thing that can happen - after all, falling back to any is

just the plain JavaScript experience anyway.

function greet(person, date) { console.log(Hello ${person}, today is ${date.toDateString()}!); } greet("Maddison", new Date());

However, using any often defeats the purpose of using TypeScript in the first place. The more

typed your program is, the more validation and tooling you'll get, meaning you'll run into fewer

bugs as you code. Turning on the noImplicitAny flag will issue an error on any variables whose

type is implicitly inferred as any.

strictNullChecks

By default, values like null and undefined are assignable to any other type. This can make

writing some code easier, but forgetting to handle null and undefined is the cause of countless

bugs in the world - some consider it a billion dollar mistake! The strictNullChecks flag makes

handling null and undefined more explicit, andspares us from worrying about whether we

forgot to handle null and undefined.

any

TypeScript also has a special type, any , that you can use whenever you don't want a particular

value to cause typechecking errors.

When a value is of type any , you can access any properties of it (which will in turn be of type

any ), call it like a function, assign it to (or from) a value of any type, or pretty much anything else

that's syntactically legal:

The any type is useful when you don't want to write out a long type just to convince TypeScript

that a particular line of code is okay.

noImplicitAny

When you don't specify a type, and TypeScript can't infer it from context, the compiler will typically

default to any.

You usually want to avoid this, though, because any isn't type-checked. Use the compiler flag

noImplicitAny to flag any implicit any as an error.

Type Annotations on Variables

When you declare a variable using const , var , or let , you can optionally add a type annotation

to explicitly specify the type of the variable:

let obj: any = { x: 0 }; // None of the following lines of code will throw compiler errors. // Using any disables all further type checking, and it is assumed // you know the environment better than TypeScript. obj.foo(); obj(); obj.bar = 100; obj = "hello"; const n: number = obj;

let myName: string = "Alice";

TypeScript doesn't use "types on the left"-style declarations like int x = 0; Type annotations will always goafter the thing being typed.

In most cases, though, this isn't needed. Wherever possible, TypeScript tries to automaticallyinfer

the types in your code. For example, the type of a variable is inferred based on the type of its

initializer:

For the most part you don't need to explicitly learn the rules of inference. If you're starting out, try

using fewer type annotations than you think - you might be surprised how few you need for

TypeScript to fully understand what's going on.

Functions

Functions are the primary means of passing data around in JavaScript. TypeScript allows you to

specify the types of both the input and output values of functions.

Parameter Type Annotations

When you declare a function, you can add type annotations after each parameter to declare what

types of parameters the function accepts. Parameter type annotations go after the parameter name:

When a parameter has a type annotation, arguments to that function will be checked:

// No type annotation needed -- 'myName' inferred as type 'string' let myName = "Alice";

// Parameter type annotation function greet(name: string) { console.log("Hello, " + name.toUpperCase() + "!!"); }

// Would be a runtime error if executed! greet(42);

Argument of type 'number' is not assignable to parameter of type 'string'.

Argument of type 'number' is not assignable to parameter of type 'string'.