The Type System
- Catch errors during development
- Type annotations analyze the code
- Only active during development
- Doesn't perform any optimization!
- Compiles the code to old plain JS!
The Type
- Refer properties and functions that a value has.
- A value is anything contained inside of a variable.
- Examples:
- string, number, boolean, Date, Todo (custom interface)
- Primitive types: number, boolean, void, undefined, string, symbol, null
- Object Types: functions, arrays, classes, objects
// Hover over the variables to see what type they are
const today = new Date();
today.getMonth();
const person = { age: 20 };
class Color {}
const red = new Color();
Type inference
- Automatically figure out what kind of value a variable has
Type Annotations
- Indicate the type of value a variable has
- Elements
// Variable
let speed: string = 'fast';
// Function
const logger = (message: string): void => {
console.log(message);
};
// Object
const { age }: { age: number } = profile; // Object destructuring
// Array
const carMakers: string[] = [];
// Tuple
const pepsi: [string, boolean, number] = ['brown', true, 40];
// Class
class Vehicle {
color: string;
protected honk(): void {
console.log('Beep!');
}
constructor(public color: string) {}
}
// Personalized object
const events: { [key: string]: () => void } = {}; // Object that stores events (that store callback arrays)
eventsMap(): { [key: string]: () => void } {
return {
'click:button': this.onButtonClick
};
Type alias
// Tuple
type MatchData = [Date, string, string, number];
// Customizable string types
type BestName = 'Henrique';
function printName(name: BestName) {
console.log(name); // Receive only 'Henrique' as name
}
Type guard
- Restore the full access of the class methods and properties
function printAnything(thing: number | string): void {
// For primitive types (e.g. number, string, boolean, symbol)
if (typeof someInstance === 'string') {
thing.toString(); // autocomplete for toString() would be enabled!
}
if (typeof someInstance === 'number') {
thing.toLowerCase(); // autocomplete for toLowerCase() would be enabled!
}
if (someInstance instanceof SomeClass) {
// Type guard for other types (classes). E.g. Array (number) ...
}
console.log(thing);
}
Type assertion
- Stablish with will be the object type
- It's used when an outcome can have multiple types
let someValue: any = 'this is a string';
let strLength: number = (<string>someValue).length;
let someValue: any = 'this is a string';
let strLength: number = (someValue as string).length;