TypeScript Basics
A practical walkthrough of TypeScript from primitives to generics, narrowing and discriminated unions, with runnable examples for each idea.
On this page
Introduction
TypeScript is a superset of JavaScript, providing type safety and static type checking. It is a statically-typed language.
In statically typed languages, the data type of a variable is known at compile time, while in dynamically typed languages, the data type is assigned during runtime by the interpreter, depending on its value.
Usage
TypeScript is primarily a development tool, where the project still runs JavaScript.
Syntax
Running TypeScript
.ts program, follow these steps:The first step involves transpiling, where the TypeScript compiler transpiles the TypeScript code to JavaScript. Transpiling is the process of converting the source code from one programming language to another. It is often used in web development, especially with languages like TypeScript and JSX, which are not directly supported by web browsers.
Primitive Types
In TypeScript, primitive types such as string, number, and boolean are used to represent basic data types.
Note: JavaScript does not have a special runtime value for TypeScript types, so there's no equivalent to "int" or "float" - everything is simply number.
However, it's not always necessary to explicitly specify types. In some cases, TypeScript can infer types based on the assigned values. Overusing types can make the code verbose and less readable.
any
any. However, using any is discouraged as it disables type checking. It's recommended to specify types explicitly or use the compiler flag noImplicitAny to flag implicit any types as errors.Functions
Type annotations for functions are strong and recommended.
Syntax
Arrow Functions
Arrow functions provide a concise syntax for writing functions.
Default Value
Return Type
never
never type represents values that are never observed. In a return type, this means that the function throws an exception or terminates execution of the program.Objects
Assigning type to an object
Bad behaviour of objects
When a function is called with an optional parameter, it throws an error. However, if an object with an optional property is created and assigned to a variable, calling the function with that variable does not result in an error.
Type Aliases
Type Aliase is a name for any type. This is convenient, but it's common to want to use the same type more than once and refer to it by a single name.
Combining types
readonly & "?"(optional)
readonly is used to make a property unchangeable, the value cannot be changed after it is set. ? marks the property as optional.Arrays
[1,2,3], you can use the syntax number[], this works for any type (e.g. string[]).Union Type
|) to separate each type.Note: Direct manipulation on individual types is not allowed because TS treats the union type as a new data type.
Tuples
Tuples are typed arrays of pre-defined length and types for each index. The order of data type in each index should be maintained.
Array methods are allowed on tuples that violate type safety, so a good practice would be to make a tuple "readonly".
Enums
A special class that represents a group of constants, can be string or numeric.
First value is initialised to 0 by default then 1 is added to each additional value.
We can also set the value and have it auto increment from that.
Or we can initialise all the values.
Interfaces
Used to define shape/structure of objects. Interfaces are similar to type aliases, except they only apply to object types.
Interfaces can extend each other's definition. Extending simply means you are creating a new interface with same properties as that of the original interface, plus something new.
Interfaces vs Types
Declaration Syntax
Type: Types can be used to define simple types, union types, intersection types, and more.
Interface: Interfaces are typically used for defining object shapes.
Extending/Implementing
extends clause. You build on one with an intersection instead, and a class can implement a type alias as long as it names an object shape rather than a union.Interface: Interfaces can extend other interfaces and can be implemented by classes.
Declaration Merging
Type: Types don't support declaration merging.
Interface: Interfaces support declaration merging, which means you can declare an interface multiple times, and their members will be merged.
Setting up TypeScript for projects (Node.js)
- Create
tsconfig.jsonfile
tsconfig.json is a configuration file used by the TypeScript compiler (tsc) to specify compiler options and project settings for a TypeScript project. This file allows developers to define various settings such as compilation target, module system, output directory, and more.- Initialise Node Package Manager
-
Create
distandsrcfolders. -
Create
index.htmlfile and make it point toindex.jsin thedistfolder by adding a script tag. -
Create
index.tsin thesrcfolder. -
Specify output directory in
tsconfig.json
dist directory.-
Add content to your
.tsfile. -
Compile and run
.tsfile.
This command runs TypeScript files in "watch mode", allowing the compiler to detect changes and recompile automatically.
Classes
TypeScript offers full support for the class keyword introduced in ES2015.
Here’s the most basic class - an empty one:
Fields
public writeable property on a class.Getters & Setters
-
A getter method returns the property’s value. A getter is also called an accessor.
-
A setter method updates the property’s value. A setter is also known as a mutator.
-
A getter method starts with the keyword
getand a setter method starts with the keywordset.
Note: A set accessor cannot have a return type annotation.
Interfaces can be implemented by classes.
Inheritance
extends keyword.-
privatekeyword: private access modifier makes the field only accesssible inside a class. -
protectedkeyword: protected members are only visible to subclasses of the class they’re declared in. -
superkeyword: It allows us to invoke constructor of parent class, call parent class methods within a subclass. Thesuperkeyword is useful for overriding and extending the behavior of methods defined in a parent class, especially when those methods are not declared asprivate.
super call. Super must be called before accessing this in the constructor of a derived class.Abstract classes
abstract keyword. Abstract classes are mainly for inheritance where other classes may derive from them. We cannot create an instance of an abstract class.An abstract class typically includes one or more abstract methods or property declarations. The class which extends the abstract class must define all the abstract methods.
Generics
Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use.
They allow you to create reusable components (such as functions, classes, or interfaces) that can work with any data type while still providing type safety.
any is certainly generic in that it will cause the function to accept any and all types for the type of arg, we actually are losing the information about what that type was when the function returns. If we passed in a number, the only information we have is that any type could be returned.Instead, we need a way of capturing the type of the argument in such a way that we can also use it to denote what is being returned. Here, we will use a type variable, a special kind of variable that works on types rather than values.
Custom generic interface
Pair<T, U>, T and U are placeholders for the actual types that will be used when instances of Pair are created. This allows you to create instances of Pair with different types for the first and second properties without having to define a separate interface for each combination of types.Passing an array and using arrow functions
Extending a generic type
Generic class
Type Narrowing
Type narrowing in TypeScript refers to the process of refining the type of a variable within a certain block of code based on certain conditions. This helps TypeScript infer more specific types, improving type safety and enabling better code optimization.
While it might not look like much, there’s actually a lot going on under the covers here. Much like how TypeScript analyzes runtime values using static types, it overlays type analysis on JavaScript’s runtime control flow constructs like if/else, conditional ternaries, loops, truthiness checks, etc., which can all affect those types.
in operator
in operator is used for type narrowing, which means it helps narrow down the type of an object, based on wether a property exists within it. It's particularly useful when working with union or discriminated types.instanceof operator
instanceof keyword is used to check whether an object is an instance of a particular class or constructor function. It returns true if the object is an instance of the specified class or its subclasses; otherwise, it returns false.Type predicate
A type predicate is a way to assert the type of a variable within a conditional statement. It allows you to narrow down the type of a variable within a certain block of code, based on some condition.
isFish function, we define a type predicate pet is Fish, indicating that if the condition (pet as Fish).swim !== undefined is true, then pet is indeed a Fish. Within the feedPet function, when we call isFish(pet), TypeScript narrows down the type of pet to Fish if the condition is met, allowing us to safely call pet.swim() without TypeScript throwing errors.Discriminated Union & Exhaustive Checking
kind in this case)Exhaustive checking refers to ensuring that all possible cases of the discriminated union are handled within a switch statement or if-else chain. This helps TypeScript catch errors where you might forget to handle a specific case, ensuring that your code is more robust.
never type is used to indicate that a value should never occur. When used in the context of exhaustive checking with discriminated unions, it helps TypeScript ensure that all possible cases are handled, leaving no room for unexpected values.Every example in this post lives in a repository. Browse it, raise an issue, or send a fix.
View the repository