Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Few technologies in the last few years had the impact that TypeScript had.
Let me add a little bit of social proof in favor of TypeScript.
The “The State of JavaScript 2018” survey, almost 50% of respondents said they used TypeScript, and would use it again. over 30% said they would like to learn it. That’s a huge percentage of people interested in it.
TypeScript is built by Microsoft, which is not new to creating programming languages, and one of its creators is Anders Hejlsberg, a danish software engineer who is known for Turbo Pascal (❤️) and Delphi. I put the heart next to Turbo Pascal because Pascal was my first programming language and we used Turbo Pascal at school.
It’s an open source language, developed in public at https://github.com/Microsoft/TypeScript.
Angular is all about TypeScript, Vue.js is said to make version 3 using TypeScript. Ryan Dahl, the creator of Node.js, said great things about it too.
I think those things help you put TypeScript in perspective. It’s not just a random JavaScript flavor that will die next month, it’s definitely here to stay. And as things go, this means you are likely required to use it in a future project, or at your next job. Maybe it will help you get a job too, so let’s just dive into it.
Write and compile your first TypeScript file
Starting with TypeScript is easy. If you ever wrote a line of JavaScript, you already wrote TypeScript code!
This odd statement I made is one of the reasons for TypeScript’s success: it’s a strict superset of JavaScript.
It’s a bit like what SCSS is for CSS.
In particular, it’s a superset of ECMAScript 2015 (also known as ES6). This means that any valid JavaScript is also valid TypeScript.
Many of the features of TypeScript are equivalent to the JavaScript ones. For example variables, the module system, iterators and more.
So, there’s no need to write your absolute first TypeScript file, because you already did without knowing so, but let’s make a little “hello world!” by explicitly making a TypeScript file, and compile that to JavaScript.
Run npm install -g typescript
to globally install the TypeScript compiler, available to you using the tsc
command.
Make a new folder, and create an app.ts
file. ts
is the TypeScript file extension.
Write this first program:
const greet = () => {
console.log('Hello world!')
}
greet()
This is just plain JavaScript, but stored in a .ts
file.
Now compile the program using tsc app.ts
. The result will be a new JavaScript file: app.js
, with this content:
var greet = function () {
console.log('Hello world!');
};
greet();
The TypeScript code has been compiled to JavaScript. The JavaScript code changed a little bit, for example you can notice it added semicolons, and used var
instead of const
, and used a regular function instead of the arrow function.
It looks like old JavaScript, right? This is because TypeScript compiles to ES5 by default, as this is the ECMAScript version that is almost guaranteed to be supported in all modern browsers. You can change the compilation target to other versions,for example to target ES2018 use tsc app.ts --target ES2018
:
const greet = () => {
console.log('Hello world!');
};
greet();
See, here almost nothing changed from our original .ts
file except for the additional semicolons.
There is a very convenient online playground that lets you play around with the TypeScript to JavaScript compilation, at https://www.typescriptlang.org/play/.
Typing
Typing is the key TypeScript feature.
So far we compiled a .ts
file, but we just compiled plain JavaScript.
You saw one first feature of TypeScript: you can use modern JavaScript and compile it to ES5 (or higher), kind of what Babel does.
We didn’t use any of the TypeScript functionalities.
The most important piece of functionality provided by TypeScript is the type system: static types, interfaces, type inference, enums, hybrid types, generics, union/intersection types, access modifiers, null checking.
If you ever used a typed language, like Go or C, you already know how this works. If not, and you only programmed in a dynamic language like Python or Ruby, this is all new to you but don’t worry.
The type system allows you, for example, to add types to your variables, function arguments and function return types, giving a more rigid structure to your programs.
The advantages are better tooling: the compiler (and editors like editors like VS Code) can help you a lot during development, pointing out bugs as you write the code. Bugs that couldn’t possibly be detected if you didn’t have types. Also, teamwork gets easier because the code is more explicit.
The resulting JavaScript code that we compile to does not have types, of course: they are lost during the compilation phase, but the compiler will point out any error it finds.
Here is how you define a string variable in TypeScript:
const greeting : string = "hello!"
Type inference lets us avoid writing the type in obvious cases like this:
const greeting = "hello!"
The type is determined by TS.
This is how a function accepts an argument of a specific type:
const multiply = (a: number, b: number) => {
return a * b
}
If you pass a string to multiply()
, the compiler will give you an error.
Here is how functions declare their return value:
const multiply = (a: number, b: number): number => {
return a * b
}
Valid types are
number
string
boolean
enum
void
null
undefined
any
never
Array
tuple
any
is a catch-all type that identifies, as its name says, any type.
Classes
ES2015/ES6 added classes to JavaScript, as a simple syntactic sugar over the prototypal inheritance.
Like it or not, under the hoods JavaScript is still using prototypal inheritance, with all its unique features and quirks.
TypeScript classes are a little bit different than JavaScript classes. The reason is that TypeScript introduced classes before JavaScript had them (they were introduced in ES2015/ES6).
Like in JavaScript, you declare classes in this way:
class Car {
}
This is how you define class fields:
class Car {
color: string
}
All fields are public by default. You can set a field to be private or protected:
class Car {
public color: string
private name: string
protected brand: string
}
Like it happens in other programming languages, private fields can only be accessed in the class that declares them. Protected fields can only be accessed by deriving classes as well.
You can also declare static fields, which are class fields rather than object fields:
class Car {
static numberOfWheels = 4
}
You can initialize fields with a constructor:
class Car {
color: string
constructor(theColor: string) {
this.color = theColor
}
}
This shorthand syntax makes it simpler:
class Car {
constructor(public color: string) {}
printColor() {
alert(this.color)
}
}
(new Car('red')).printColor()
Notice how we referenced the class field using this.x
.
A field can also be read only:
class Car {
readonly color: string
}
and in this case its value can only be set in the constructor.
Classes have methods:
class Car {
color: string
constructor(public color: string) {
this.color = color
}
drive() {
console.log('You are driving the car')
}
}
Like in plain JavaScript, you create objects from those classes, using the new
keyword:
const myCar = new Car('red')
and you can extend an existing class using the extend
keyword:
class ElectricCar extends Car {
//...
}
You can call super()
in the constructor and in methods to call the extended class corresponding method.
Accessors
Fields can have getters and setters. Example:
class Car {
private _color: string
get color(): string {
return this._color
}
set color(color: string) {
this._color = color
}
}
Abstract classes
Classes can be defined as abstract, which means there needs to be a class that extends it, and implements its eventual abstract methods:
abstract class Car {
abstract drive()
}
class SportsCar extends Car {
drive() {
console.log('You are driving a sports car')
}
}
Interfaces
Interfaces build upon basic types. You can use an interface as a type, and this interface can contain other type definitions:
interface SetOfNumbers {
a: number;
b: number;
}
const multiply = (set: SetOfNumbers) => {
return set.a * set.b
}
multiply({ a:1, b: 2 })
An interface can also be an interface for a class implementation:
interface Car {
name: 'string'
new (brand: string)
drive(): void
}
class SportsCar implements Car {
public name
construtor(public brand: string) {
//...
}
drive() {
console.log('You are driving a sports car')
}
}
Functions features
Functions can have optional parameters using the ?
symbol after the parameter name:
class Car {
drive(kilometers?: number) {
if (kilometers) {
console.log(`Drive the car for ${kilometers} kilometers`)
} else {
console.log(`Drive the car`)
}
}
}
and parameters can also have default values:
class Car {
drive(kilometers = 10) {
console.log(`Drive the car for ${kilometers} kilometers`)
}
}
A function can accept a varying number of parameters by using rest parameters:
class Car {
drive(kilometers = 10, ...occupants: string[]) {
console.log(`Drive the car for ${kilometers} kilometers, with those people on it:`)
occupants.map((person) => console.log(person))
}
}
(new Car()).drive(20, 'Flavio', 'Roger', 'Syd')
Enums
Enums are one great way to define named constants, which is unfortunately not supported by JavaScript, but popularized by other languages.
TypeScript gives us enums:
enum Order {
First,
Second,
Third,
Fourth
}
TS internally assigns an unique identifier to each of those values, and we can reference Order.First
, Order.Second
and so on.
You can assign values to the constants explicitly:
enum Order {
First = 0,
Second = 1,
Third = 2,
Fourth = 3
}
or also use strings:
enum Order {
First = 'FIRST',
Second = 'SECOND',
Third = 'THIRD',
Fourth = 'FOURTH'
}
Generics
Generics is a feature that’s part of many different programming languages. In short, you can create a function, interface or class that works with different types, without specifying the type up front.
But at compile time, if you start using that function with a type and then you change type (e.g. from number to string), the compiler will throw an error.
We could do this by omitting types at all or using any
, but with generics all the tooling is going to be able to help us.
Example syntax:
function greet<T>(a : T) {
console.log(`Hi ${a}!`)
}
greet('Flavio')
The funny T
symbol identifies a generic type.
The type can be restricted to a certain class family or interface, using the extends
keyword:
interface Greetable { name: string }
function greet<T extends Greetable>(a : T) {
alert(`Hi ${a.name}!`)
}
greet({ name: 'Flavio'})
I am ready for more!
Those are the basics of TypeScript. Go ahead to the official docs to learn all the details, or start writing your apps and learn as you do!
Download my free JavaScript Beginner's Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More js tutorials:
- Things to avoid in JavaScript (the bad parts)
- Deferreds and Promises in JavaScript (+ Ember.js example)
- How to upload files to the server using JavaScript
- JavaScript Coding Style
- An introduction to JavaScript Arrays
- Introduction to the JavaScript Programming Language
- The Complete ECMAScript 2015-2019 Guide
- Understanding JavaScript Promises
- The Lexical Structure of JavaScript
- JavaScript Types
- JavaScript Variables
- A list of sample Web App Ideas
- An introduction to Functional Programming with JavaScript
- Modern Asynchronous JavaScript with Async and Await
- JavaScript Loops and Scope
- The Map JavaScript Data Structure
- The Set JavaScript Data Structure
- A guide to JavaScript Template Literals
- Roadmap to Learn JavaScript
- JavaScript Expressions
- Discover JavaScript Timers
- JavaScript Events Explained
- JavaScript Loops
- Write JavaScript loops using map, filter, reduce and find
- The JavaScript Event Loop
- JavaScript Functions
- The JavaScript Glossary
- JavaScript Closures explained
- A tutorial to JavaScript Arrow Functions
- A guide to JavaScript Regular Expressions
- How to check if a string contains a substring in JavaScript
- How to remove an item from an Array in JavaScript
- How to deep clone a JavaScript object
- Introduction to Unicode and UTF-8
- Unicode in JavaScript
- How to uppercase the first letter of a string in JavaScript
- How to format a number as a currency value in JavaScript
- How to convert a string to a number in JavaScript
- this in JavaScript
- How to get the current timestamp in JavaScript
- JavaScript Strict Mode
- JavaScript Immediately-invoked Function Expressions (IIFE)
- How to redirect to another web page using JavaScript
- How to remove a property from a JavaScript object
- How to append an item to an array in JavaScript
- How to check if a JavaScript object property is undefined
- Introduction to ES Modules
- Introduction to CommonJS
- JavaScript Asynchronous Programming and Callbacks
- How to replace all occurrences of a string in JavaScript
- A quick reference guide to Modern JavaScript Syntax
- How to trim the leading zero in a number in JavaScript
- How to inspect a JavaScript object
- The definitive guide to JavaScript Dates
- A Moment.js tutorial
- Semicolons in JavaScript
- The JavaScript Arithmetic operators
- The JavaScript Math object
- Generate random and unique strings in JavaScript
- How to make your JavaScript functions sleep
- JavaScript Prototypal Inheritance
- JavaScript Exceptions
- How to use JavaScript Classes
- The JavaScript Cookbook
- Quotes in JavaScript
- How to validate an email address in JavaScript
- How to get the unique properties of a set of objects in a JavaScript array
- How to check if a string starts with another in JavaScript
- How to create a multiline string in JavaScript
- The ES6 Guide
- How to get the current URL in JavaScript
- The ES2016 Guide
- How to initialize a new array with values in JavaScript
- The ES2017 Guide
- The ES2018 Guide
- How to use Async and Await with Array.prototype.map()
- Async vs sync code
- How to generate a random number between two numbers in JavaScript
- HTML Canvas API Tutorial
- How to get the index of an iteration in a for-of loop in JavaScript
- What is a Single Page Application?
- An introduction to WebAssembly
- Introduction to JSON
- The JSONP Guide
- Should you use or learn jQuery in 2020?
- How to hide a DOM element using plain JavaScript
- How to merge two objects in JavaScript
- How to empty a JavaScript array
- How to encode a URL with JavaScript
- How to set default parameter values in JavaScript
- How to sort an array of objects by a property value in JavaScript
- How to count the number of properties in a JavaScript object
- call() and apply() in JavaScript
- Introduction to PeerJS, the WebRTC library
- Work with objects and arrays using Rest and Spread
- Destructuring Objects and Arrays in JavaScript
- The definitive guide to debugging JavaScript
- The TypeScript Guide
- Dynamically select a method of an object in JavaScript
- Passing undefined to JavaScript Immediately-invoked Function Expressions
- Loosely typed vs strongly typed languages
- How to style DOM elements using JavaScript
- Casting in JavaScript
- JavaScript Generators Tutorial
- The node_modules folder size is not a problem. It's a privilege
- How to solve the unexpected identifier error when importing modules in JavaScript
- How to list all methods of an object in JavaScript
- The String replace() method
- The String search() method
- How I run little JavaScript snippets
- The ES2019 Guide
- The String charAt() method
- The String charCodeAt() method
- The String codePointAt() method
- The String concat() method
- The String endsWith() method
- The String includes() method
- The String indexOf() method
- The String lastIndexOf() method
- The String localeCompare() method
- The String match() method
- The String normalize() method
- The String padEnd() method
- The String padStart() method
- The String repeat() method
- The String slice() method
- The String split() method
- The String startsWith() method
- The String substring() method
- The String toLocaleLowerCase() method
- The String toLocaleUpperCase() method
- The String toLowerCase() method
- The String toString() method
- The String toUpperCase() method
- The String trim() method
- The String trimEnd() method
- The String trimStart() method
- Memoization in JavaScript
- The String valueOf() method
- JavaScript Reference: String
- The Number isInteger() method
- The Number isNaN() method
- The Number isSafeInteger() method
- The Number parseFloat() method
- The Number parseInt() method
- The Number toString() method
- The Number valueOf() method
- The Number toPrecision() method
- The Number toExponential() method
- The Number toLocaleString() method
- The Number toFixed() method
- The Number isFinite() method
- JavaScript Reference: Number
- JavaScript Property Descriptors
- The Object assign() method
- The Object create() method
- The Object defineProperties() method
- The Object defineProperty() method
- The Object entries() method
- The Object freeze() method
- The Object getOwnPropertyDescriptor() method
- The Object getOwnPropertyDescriptors() method
- The Object getOwnPropertyNames() method
- The Object getOwnPropertySymbols() method
- The Object getPrototypeOf() method
- The Object is() method
- The Object isExtensible() method
- The Object isFrozen() method
- The Object isSealed() method
- The Object keys() method
- The Object preventExtensions() method
- The Object seal() method
- The Object setPrototypeOf() method
- The Object values() method
- The Object hasOwnProperty() method
- The Object isPrototypeOf() method
- The Object propertyIsEnumerable() method
- The Object toLocaleString() method
- The Object toString() method
- The Object valueOf() method
- JavaScript Reference: Object
- JavaScript Assignment Operator
- JavaScript Internationalization
- JavaScript typeof Operator
- JavaScript new Operator
- JavaScript Comparison Operators
- JavaScript Operators Precedence Rules
- JavaScript instanceof Operator
- JavaScript Statements
- JavaScript Scope
- JavaScript Type Conversions (casting)
- JavaScript Equality Operators
- The JavaScript if/else conditional
- The JavaScript Switch Conditional
- The JavaScript delete Operator
- JavaScript Function Parameters
- The JavaScript Spread Operator
- JavaScript Return Values
- JavaScript Logical Operators
- JavaScript Ternary Operator
- JavaScript Recursion
- JavaScript Object Properties
- JavaScript Error Objects
- The JavaScript Global Object
- The JavaScript filter() Function
- The JavaScript map() Function
- The JavaScript reduce() Function
- The JavaScript `in` operator
- JavaScript Operators
- How to get the value of a CSS property in JavaScript
- How to add an event listener to multiple elements in JavaScript
- JavaScript Private Class Fields
- How to sort an array by date value in JavaScript
- JavaScript Public Class Fields
- JavaScript Symbols
- How to use the JavaScript bcrypt library
- How to rename fields when using object destructuring
- How to check types in JavaScript without using TypeScript
- How to check if a JavaScript array contains a specific value
- What does the double negation operator !! do in JavaScript?
- Which equal operator should be used in JavaScript comparisons? == vs ===
- Is JavaScript still worth learning?
- How to return the result of an asynchronous function in JavaScript
- How to check if an object is empty in JavaScript
- How to break out of a for loop in JavaScript
- How to add item to an array at a specific index in JavaScript
- Why you should not modify a JavaScript object prototype
- What's the difference between using let and var in JavaScript?
- Links used to activate JavaScript functions
- How to join two strings in JavaScript
- How to join two arrays in JavaScript
- How to check if a JavaScript value is an array?
- How to get last element of an array in JavaScript?
- How to send urlencoded data using Axios
- How to get tomorrow's date using JavaScript
- How to get yesterday's date using JavaScript
- How to get the month name from a JavaScript date
- How to check if two dates are the same day in JavaScript
- How to check if a date refers to a day in the past in JavaScript
- JavaScript labeled statements
- How to wait for 2 or more promises to resolve in JavaScript
- How to get the days between 2 dates in JavaScript
- How to upload a file using Fetch
- How to format a date in JavaScript
- How to iterate over object properties in JavaScript
- How to calculate the number of days between 2 dates in JavaScript
- How to use top-level await in ES Modules
- JavaScript Dynamic Imports
- JavaScript Optional Chaining
- How to replace white space inside a string in JavaScript
- JavaScript Nullish Coalescing
- How to flatten an array in JavaScript
- This decade in JavaScript
- How to send the authorization header using Axios
- List of keywords and reserved words in JavaScript
- How to convert an Array to a String in JavaScript
- How to remove all the node_modules folders content
- How to remove duplicates from a JavaScript array
- Let vs Const in JavaScript
- The same POST API call in various JavaScript libraries
- How to get the first n items in an array in JS
- How to divide an array in multiple equal parts in JS
- How to slow down a loop in JavaScript
- How to load an image in an HTML canvas
- How to cut a string into words in JavaScript
- How to divide an array in half in JavaScript
- How to write text into to an HTML canvas
- How to remove the last character of a string in JavaScript
- How to remove the first character of a string in JavaScript
- How to fix the TypeError: Cannot assign to read only property 'exports' of object '#<Object>' error
- How to create an exit intent popup
- How to check if an element is a descendant of another
- How to force credentials to every Axios request
- How to solve the "is not a function" error in JavaScript
- Gatsby, how to change the favicon
- Loading an external JS file using Gatsby
- How to detect dark mode using JavaScript
- Parcel, how to fix the `regeneratorRuntime is not defined` error
- How to detect if an Adblocker is being used with JavaScript
- Object destructuring with types in TypeScript
- The Deno Handbook: a concise introduction to Deno 🦕
- How to get the last segment of a path or URL using JavaScript
- How to shuffle elements in a JavaScript array
- How to check if a key exists in a JavaScript object
- Event bubbling and event capturing
- event.stopPropagation vs event.preventDefault() vs. return false in DOM events
- Primitive types vs objects in JavaScript
- How can you tell what type a value is, in JavaScript?
- How to return multiple values from a function in JavaScript
- Arrow functions vs regular functions in JavaScript
- In which ways can we access the value of a property of an object?
- What is the difference between null and undefined in JavaScript?
- What's the difference between a method and a function?
- What are the ways we can break out of a loop in JavaScript?
- The JavaScript for..of loop
- What is object destructuring in JavaScript?
- What is hoisting in JavaScript?
- How to change commas into dots with JavaScript
- The importance of timing when working with the DOM
- How to reverse a JavaScript array
- How to check if a value is a number in JavaScript
- How to accept unlimited parameters in a JavaScript function
- JavaScript Proxy Objects
- Event delegation in the browser using vanilla JavaScript
- The JavaScript super keyword
- Introduction to XState
- Are values passed by reference or by value in JavaScript?
- Custom events in JavaScript
- Custom errors in JavaScript
- Namespaces in JavaScript
- A curious usage of commas in JavaScript
- Chaining method calls in JavaScript
- How to handle promise rejections
- How to swap two array elements in JavaScript
- How I fixed a "cb.apply is not a function" error while using Gitbook
- How to add an item at the beginning of an array in JavaScript
- Gatsby, fix the "cannot find module gatsby-cli/lib/reporter" error
- How to get the index of an item in a JavaScript array
- How to test for an empty object in JavaScript
- How to destructure an object to existing variables in JavaScript
- The Array JavaScript Data Structure
- The Stack JavaScript Data Structure
- JavaScript Data Structures: Queue
- JavaScript Data Structures: Set
- JavaScript Data Structures: Dictionaries
- JavaScript Data Structures: Linked lists
- JavaScript, how to export a function
- JavaScript, how to export multiple functions
- JavaScript, how to exit a function
- JavaScript, how to find a character in a string
- JavaScript, how to filter an array
- JavaScript, how to extend a class
- JavaScript, how to find duplicates in an array
- JavaScript, how to replace an item of an array
- JavaScript Algorithms: Linear Search
- JavaScript Algorithms: Binary Search
- JavaScript Algorithms: Selection Sort
- JavaScript Algorithms: Quicksort
- JavaScript Algorithms: Merge Sort
- JavaScript Algorithms: Bubble Sort
- Wait for all promises to resolve in JavaScript