Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Get unlimited access to the best of Medium for less than $1/week.

Become a member

TypeScript — Crash Course


Jan Cibulka · Follow
4 min read · Feb 17, 2022

Listen Share More


TypeScript is an open-source language built on top of JavaScript. It offers everything
that JavaScript does, plus some additional features.

The main benefit of TypeScript is the ability to use static types. Hence the name
“type-script”.

What do I mean by static types?

Dynamically and statically typed languages


Dynamically typed languages (JavaScript, Python, Ruby, PHP) don’t specify types
when creating variables. For example, you can do the following in JavaScript:
1 let price; // defining a variable, not specifying any type
2 price = 123; // now the variable holds a number type
3 price = "123"; // now the same variable holds a string type
4 // That might cause hard-to-spot bugs...

1-typescript-crash-course.js hosted with ❤ by GitHub view raw

Statically typed languages (TypeScript, Java, C++, Rust, Go) require that you
explicitly assign types to variables, function parameters, return values, etc. Such
languages might require some extra work from the programmer upfront, but
ultimately help to prevent bugs and undesirable program behavior later.

Soon, we will get to an example of how TypeScript code looks like. But first, let’s
install it.

How to use TypeScript


Run the following command to install TypeScript as a dev dependency:

npm install typescript --save-dev

Since TypeScript is just a super-set of JavaScript, it needs to be compiled down to


regular JavaScript so that the code can actually be executed. The TSC (TypeScript
Compiler) takes care of that. You can use a special file tsconfig.json to configure
how TypeScript works in your environment and how it should be compiled to
JavaScript. You don’t have to worry about that now, the default settings are
sufficient.

Start using TypeScript by creating a file index.ts . Notice the file extension. Instead
of a regular JavaScript file extension .js, we use .ts for TypeScript (or .tsx, if you
want to use JSX syntax like in React).

Let’s rewrite the JavaScript code from the beginning of this article into TypeScript:

1 let price: number; // Here we explicitly state that the variable price should be a number
2 price = 123; // This will work
3 price = "123"; // This will throw an error
4 let anotherPrice: number = 123; // We can define the type and assign value on one line as well

2-typescript-crash-course.ts hosted with ❤ by GitHub view raw


You see that the difference is really tiny. We just declared a variable type on row #1.

When you delete row #3 which now throws an error, you can run the TypeScript
Compiler on the file by writing this command in your console:

tsc index.ts

This will generate a new file index.js which contains the code converted to simple
JavaScript so that the browsers and Node.JS understand it.

You can also set the TypeScript Compiler to automatically compile your file on every
save with this command:

tsc --watch index.ts

Let’s now have a look at the different types of variables that we can actually declare.

Basic Types in TypeScript


The most basic types are:

number

string

boolean

If you want your variable to take any type, you can simply use:

any

Let’s have a look at the actual code:

1 let price: number = 5;


2 let product: string = "Daily Prophet";
3 let isInStock: boolean = true;
4 let buyers: any = "Wizarding World"; // this variable can take any type
5
6 buyers = true; // so we can assign a value of another type to buyers;

3-typescript-crash-course.ts hosted with ❤ by GitHub view raw


If we want to be a little more specific than any , we can use a union of several types.
The syntax for that uses the pipe character dividing any possible types as in: type |

type | type .

1 let sellers: number | string = "Ten sellers";


2 sellers = 10; // number is accepted as well

6-typescript-crash-course.ts hosted with ❤ by GitHub view raw

Type Assertions
Let’s say we have a variable that can hold any type. We want to create another
variable with a more specific type and assign it the value of the first one. That’s
when we can use Type Assertion. For example:

1 let headcount: any = 1000; // any value type accepted here


2
3 // We want to have only the number type in a new variable studentsAtHogwarts
4 // So we can use Type Assertion
5
6 // Syntax option #1, which works in .ts as well as .tsx
7 let studentsAtHogwarts1 = headcount as number;
8
9 // Syntax option #2, which works in .ts only
10 let studentsAtHogwarts2 = <number> headcount;

type-assertions.ts hosted with ❤ by GitHub view raw

Arrays in TypeScript
Array holds multiple values in a sequence. There are two ways of declaring an array
in TypeScript:

1. Using square brackets with syntax elementType[]

2. Using a generic array type with syntax Array<elementType>

Here comes a demonstration of both types.

1 let games: string[] = ["Wizard's Chess", "Quidditch", "Gobstones"]


2 let publications: Array<string> = ["Daily Prophet", "The Quibbler", "Witch Weekly"];

4-typescript-crash-course.ts hosted with ❤ by GitHub view raw

Tuples in TypeScript
Similar to arrays, tuples hold multiple elements in a sequence. However, we can
specify a different type for each element.

The syntax is [elementType, elementType, elementType] and so on.

It’s also possible to create an array of tuples, which would have a syntax like this:
[elementType, elementType, elementType][] — notice the extra pair of square
brackets at the end.

1 let funSpell: [number, string, boolean] = [1, "Alohomora", true]; // simple tuple
2 let idList: [number, number, number, string] = [21, 12, 33, "sixty nine"]; // another simple tup
3
4 // And now an array of tuples:
5 let tupleArray: [number, string][] = [ [5, "Expelliarmus"], [7, "Lumos"] ];

5-typescript-crash-course.ts hosted with ❤ by GitHub view raw

Functions in TypeScript
We can specify the types of parameters as well as the types of function’s return
value.

1 // Functions
2 functions castSpell(spellId: number | string, target: string) {
3 // This function takes two parameters
4 // The first parameter spellId can hold either a numeric or a string value
5 // The second parameter target can hold a string value
6 }
7
8 // The previous function could return any value as we haven't specified the return value
9 // Let's fix it now
10 function castAdvancedSpell(spellId: number | string, target: string): string {
11 // This function has to return a string
12 return "Success!";
13 }
14
15 // If we don't want the function to return anything, we can use the void keyword
16 function noReturn(): void {
17 // This function shouldn't return a value
18 }

typescript-function-declarations.ts hosted with ❤ by GitHub view raw

Generic functions in TypeScript


Generics make our code more dynamic. They are especially helpful for creating re-
usable components.

For example, let’s say we have a function for scoring students’ exams. Sometimes we
might score them numerically (eg. 100 points), other times we would use verbal
descriptions (“excellent”).

Let’s write a generic function for finding the most frequent score from all students.

1 // Notice the keyword "ScoreType"


2 // which I chose to represent a placeholder for a type that will be specified later
3 function mostCommonScore<ScoreType> (allScores: ScoreType[]): ScoreType {
4 return allScores.sort((a,b) =>
5 allScores.filter(v => v===a).length
6 - allScores.filter(v => v===b).length
7 ).pop();
8 }
9
10 // Now we can use fill the placeholder with a desired type
11 console.log(
12 mostCommonScore<number>([50, 75, 75, 100])
13 ); // -> 75
14 console.log(
15 mostCommonScore<string>(["Average", "Good", "Good", "Excellent"])
16 ); // -> Good

typescript-generic-functions.ts hosted with ❤ by GitHub view raw

Enum in TypeScript
Enums allow us to declare a set of named constants with numeric or string values.
Best to explain in code:

Open in app

Search
1 // These will get automatically assigned numerical values
2 enum bookCategories {
3 History, // -> 0
4 Beasts, // -> 1
5 Spells, // -> 2
6 }
7
8 // We can also assign our own numeric values
9 // If we omit a numeric value, automatically it will be the next in the sequence
10 enum spellStrengths {
11 Defensive = 5, // -> 5
12 Offensive, // -> 6
13 Fun = 10, // -> 10
14 }
15
16 // String values are not a problem either and we can mix them in with numerical values
17 enum spellNames {
18 Defensive = "EXPELLIARMUS", // -> EXPELLIARMUS
19 Offensive = "OBLIVIATE", // -> OBLIVIATE
20 Fun = "ALOHOMORA", // -> ALOHOMORA
21 SpellCount = 3, // -> 3
22 AnotherCount, // -> 4
23 }

7-typescript-crash-course.ts hosted with ❤ by GitHub view raw

Interface in TypeScript
Interface defines a specific structure for an object.

1 // First we define an interface


2 interface StudentOfHogwarts {
3 id: number,
4 name: string,
5 magic(spell:string): void,
6 age?: number, // notice the question mark which means this property is optional
7 readonly house: string, // the readonly property can be assigned only when the object is inst
8 }
9
10 // Now we can create an object with that interface
11 const harry: StudentOfHogwarts = {
12 id: 1,
13 name: "Harry",
14 magic: (spell) => console.log(spell),
15 house: "Gryffindor"
16 }

typescript-interface.ts hosted with ❤ by GitHub view raw


Class in TypeScript
Similarly to objects, classes can also use interfaces. We can even re-use the interface
from the previous example. Notice that we assign the type to the class with the
implements keyword.

1 // We will re-use the StudentOfHogwarts interface from the previous example


2 // Notice the "implements" keyword
3 class Student implements StudentOfHogwarts {
4 id: number
5 name: string
6
7 constructor(id: number, name: string) {
8 // Constructor is basically a method that gets called on object instantiation
9 this.id = id
10 this.name = name
11 }
12
13 magic(spell: string): string {
14 return `${this.name} cast ${spell}!`
15 }
16 }
17
18 const potter = new Student(1, "Harry");
19
20 // We can also re-use the enum type example from earlier
21 console.log(potter.magic(spellNames.Fun));
22 // -> Harry cast ALOHOMORA!

typescript-class.js hosted with ❤ by GitHub view raw

We can further extend our class. Let’s say we won’t to create a class for the next
generation of students, which would inherit the parents properties.

In addition to the extends keyword, let’s also demonstrate the private and
protected keywords.
1 // Extending the previous example with classes
2 class YoungerStudent extends Student {
3 private parents: string[]; // this property is only accessible in this class
4 protected relatives: string[]; // this is only accessible in this class and it's sub-classes
5
6 constructor(id: number, name: string, parents: string[], relatives: string[]) {
7 super(id, name); // We use the same initialization of properties as the parent-class
8 // But we don't have "parents" and "relatives" in the parent-class, so we initialize those
9 this.parents = parents;
10 this.relatives = relatives;
11 }
12
13 meetTheParents():void {
14 console.log(this.parents);
15 }
16 }
17
18 const potter2 = new YoungerStudent(2, "James", ["Harry", "Ginny"], ["Lilly", "Molly"]);
19
20 // We cannot directly read the private property "parents"
21 potter2.parents; // this will throw an error
22 // Instead, we can use a method, that reads the property within the class
23 potter2.meetTheParents();

typescript-extend-class.ts hosted with ❤ by GitHub view raw

TypeScript in React
A slightly different extension .tsx enables us to write JSX code in TypeScript.
Assuming you know React, this is how a simple component supporting TypeScript
might look like. We create an interface for props:
1 import * as React from "react";
2 import { render } from "react-dom";
3
4 export interface CustomPropsType {
5 title: string;
6 message?: string; // we set this prop to be optional
7 }
8
9 function App(props: CustomPropsType) {
10 return (
11 <>
12 <h1>{props.title}</h1>
13 <p>{props.message ? props.message : "No message available."}</p>
14 </>
15 );
16 }
17
18 render(<App title="Welcome" />, document.getElementById("root"));

typescript-react.tsx hosted with ❤ by GitHub view raw

Conclusion
Using TypeScript will make your code more resistant to bugs and unexpected
behavior. Hope this article showed you that it’s not actually that hard to start using
it.

If you found this article helpful, please click the clap 👏 button. Also, feel free to
comment! I’d be happy to help :)

Typescript JavaScript Typescript With React

Follow

Written by Jan Cibulka


52 Followers

You might also like