TypeScript Course Summary
TypeScript Course Summary
Table of Content
Getting Started…………………………………………………………………………….3
Fundamentals……………………………………………………………………………..5
Advanced Types…………………………………………………………………………..8
Generics…………………………………………………………………………………..18
Decorators………………………………………………………………………………..22
Modules…………………………………………………………………………………..26
Getting Started
Terms
Dynamically-typed Languages
IntelliSense
Refactoring
Source maps
Statically-typed Languages
Transpiling
Type safety
Summary
• Programming languages divide into two categories: statically-typed and dynamically-
typed.
• In statically-typed languages (eg C++, C#, Java, etc), the type of variables is set at
compile-time and cannot change later.
• TypeScript is essentially JavaScript with static typing and some additional features that
help us write more concise and robust code.
• Most IDEs and code editors supporting TypeScript provide incredible IntelliSense and
auto-completion. So we get active hints as we code. A great productivity booster!
• By providing type information in our code, we get better refactoring support in most
IDEs and code editors.
• Refactoring means changing the structure of the code without changing its behavior.
• Browsers don’t understand TypeScript code. So we need to use the TypeScript compiler
to compile and translate (or transpile) our TypeScript code into regular JavaScript for
execution by browsers.
• Source maps are les that represent the mapping between TypeScript and JavaScript
fi
code. They’re used for debugging.
Fundamentals
Summary
• Since TypeScript is a superset of JavaScript, it includes all the built-in types in
JavaScript (eg number, string, boolean, object, etc) as well as additional types (eg any,
unknown, never, enum, tuple, etc).
• The any type can represent any kind of value. It’s something we should avoid as much
as possible because it defeats the purpose of using TypeScript in the rst place. A
fi
variable of type any can take any kind of value!
• Tuples are xed-length arrays where each element has a speci c type. We often use
fi
fi
them for representing two or three related values.
Cheat Sheet
Annotation
let sales: number = 123_456_789;
let numbers: number[] = [1, 2, 3];
Tuples
let user: [number, string] = [1, 'Mosh'];
Enums
enum Size { Small = 1, Medium, Large };
Functions
Objects
let employee: {
id: number;
name: string;
retire: (date: Date) => void
} = {
id: 1,
name: 'Mosh',
retire: (date: Date) => {},
};
Compiler Options
Option Description
noImplicitAny When enabled, the compiler will warn you about variables
that are inferred with the any type. You’ll then have to
explicitly annotate them with any if you have a reason to
do so.
noImplicitReturns When enabled, the compiler will check all code paths in a
function to ensure they return a value.
Advanced Types
Summary
• Using a type alias we can create a new name (alias) for a type. We often use type aliases
to create custom types.
• With union types, we can allow a variable to take one of many types (eg number |
string).
• With intersection types, we can combine multiple types into one (eg Draggable &
Resizable).
• Using optional chaining (?.) we can simplify our code and remove the need for null
checks.
• Using the Nullish Coalescing Operator we can fallback to a default value when dealing
with null/unde ned objects.
fi
• Sometimes we know more about the type of a variable than the TypeScript compiler. In
those situations, we can use the as keyword to specify a different type than the one
inferred by the compiler. This is called type assertion.
• The unknown type is the type-safe version of any. Similar to any, it can represent any
value but we cannot perform any operations on an unknown type without rst
fi
narrowing to a more speci c type.
fi
• The never type represents values that never occur. We often use them to annotate
functions that never return or always throw an error.
Cheat Sheet
Type alias
type Employee = {
id: number;
name: string;
retire: (date: Date) => void
Union types
Intersection types
Literal types
Nullable types
customer?.birthdate?.getFullYear();
customers?.[0];
log?.('message');
someValue ?? 30
Type assertion
obj as Person
}
}
Compiler Options
Option Description
strictNullChecks When enabled, null and unde ned will not be
fi
acceptable values for variables unless you explicitly
declare them as nullable. So, you’ll get an error if you
set a variable to null or unde ned.
fi
allowUnreachableCode When set the false, reports error about unreachable
code.
• An object is a unit that contains some data represented by properties and operations
represented by methods.
• A class is a blueprint for creating objects. The terms class and object are often used
interchangeably.
• We use access modi ers (public, private, protected) to control access to properties and
fi
methods of a class.
• A constructor is a special method (function) within a class that is called when instances
of that class are created. We use constructors to initialize properties of an object.
• Static members are accessed using the class name. We use them where we need a single
instance of a class member (property or method) in memory.
• Inheritance allows a class to inherit and reuse members of another class. The providing
class is called the parent, super or base class while the other class is called the child, sub or
derived class.
Cheat Sheet
class Account {
id: number;
constructor(id: number) {
this.id = id;
}
}
account.id = 1;
account.deposit(10);
class Account {
readonly id: number;
nickname?: string;
}
Access modifiers
class Account {
private _balance: number;
Parameter properties
class Account {
// With parameter properties we can
// create and initialize properties in one place.
constructor(public id: number, private _balance: number) {
}
}
class Account {
private _balance = 0;
Index signatures
class SeatAssignment {
// With index signature properties we can add
// properties to an object dynamically
// without losing type safety.
[seatNumber: string]: string;
}
Static members
class Ride {
static activeRides = 0;
}
Ride.activeRides++;
Inheritance
Method overriding
Interfaces
interface Calendar {
name: string;
addEvent(): void;
}
Compiler Options
Option Description
noImplicitOverride When enabled, then compiler will warn us if we try to
override a method without using the override
keyword.
Generics
Summary
• Generics allow us to create reusable classes, interfaces and functions.
• A generic type has one or more generic type parameters speci ed in angle brackets.
fi
• When using generic types, we should supply arguments for generic type parameters or
let the compiler infer them (if possible).
• We can constrain generic type arguments by using the extends keyword after generic
type parameters.
• When extending generic classes, we have three options: can pass on generic type
parameters, so the derived classes will have the same generic type parameters.
Alternatively, we can restrict or x them.
fi
• The keyof operator produces a union of the keys of the given object.
• Using type mapping we can create new types based off of existing types. For example,
we can create a new type with all the properties of another type where these properties
are readonly, optional, etc.
• TypeScript comes with several utility types that perform type mapping for us.
Examples are: Partial<T>, Required<T>, Readonly<T>, etc.
https://www.typescriptlang.org/docs/handbook/utility-types.html
Cheat Sheet
Generic classes
Generic functions
function wrapInArray<T>(value: T) {
return [value];
}
Generic interfaces
interface Result<T> {
data: T | null;
}
Generic constraints
interface Product {
name: string;
price: number;
}
property = 'name';
property = 'price';
property = 'otherValue'; // Invalid
Type mapping
type ReadOnly<T> = {
readonly [K in keyof T]: T[K];
};
type Optional<T> = {
[K in keyof T]?: T[K];
};
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
Utility types
interface Product {
id: number;
name: string;
price: number;
}
Decorators
Summary
• Decorators are often used in frameworks (eg Angular, Vue) to chance and enhance
classes and how they behave.
• A decorator is just a function that gets called by the JavaScript runtime. In that function,
we have a chance to modify a class and its members.
fi
• We can apply more than one decorator to a class or its members. Multiple decorators
are applied in the reverse order.
Cheat Sheet
Class decorators
@Component
class ProfileComponent { }
Parameterized decorators
@Component(1)
class ProfileComponent {}
Decorator composition
Method decorators
class Person {
@Log
say(message: string) {}
}
Accessor decorators
class Person {
@Capitalize
get fullName() {}
}
Property decorators
class User {
@MinLength(4)
password: string;
}
Modules
Summary
• We use modules to organize our code across multiple les.
fi
• Objects de ned in a module are private and invisible to other modules unless exported.
fi
• We use export and import statements to export and import objects from various
modules. These statements are part of the ES6 module format.
• Over years, many module formats have been developed for JavaScript. Examples are
CommonJS (introduced by Node), AMD, UMD, etc.
• We can use the module setting in tscon g to specify the module format the compiler
fi
should use when emitting JavaScript code.
Cheat Sheet
Exporting and importing
// shapes.ts
export class Circle {}
export class Square {}
// app.ts
import { Circle, Square as MySquare } from './shapes';
Default exports
// shapes.ts
export default class Circle {}
// app.ts
import Circle from './shapes';
Wildcard imports
// app.ts
import * as Shapes from './shapes';
Re-exporting
// /shapes/index.ts
export { Circle } from './circle';
export { Square } from './square';
// app.ts
import { Circle, Square } from './shapes';
Summary
• To include JavaScript code in a TypeScript project, we need to enable the allowJs setting
in tscon g.
fi
• JavaScript code included in TypeScript projects is not type-checked by default.
fi
• We can optionally turn off compiler errors on a le-by- le basis by applying // @ts-fi
fi
nocheck once on top of JavaScript les.
fi
• When migrating a large JavaScript project to TypeScript, we might face numerous
errors. In such cases, it’s easier to disable checkJs and apply // @ts-check (the
opposite of @ts-nocheck) on individual les to migrate them one by one.
fi
• We have two ways to describe type information for JavaScript code: using JSDoc and
declaration (type de nition les).
fi
fi
• Type de nition les are similar to header les in C. They describe the features of a
fi
fi
fi
module.
• We don’t need to create type de nition les for third-party JavaScript libraries. We can
fi
fi
use type de nition les from the De nitely Typed GitHub repository (@types/
fi
fi
fi
<package>).
• Newer JavaScript libraries come with type de nition les. So there’s no need to install
fi
fi
type de nition les separately.
fi
fi
Copyright 2022 Code with Mosh codewithmosh.com