TypeScript learning notes. From zero to hero.
1. Array, Tuple, Union, Enum
// Basic Types
let id: number = 5 //Add type after variable, separated by colon
let company: string = 'Traversy Media'
let isPublished: boolean = true
let x: any = 'Hello' //any type variable can hold any type of data
let ids: number[] = [1, 2, 3, 4, 5] //Variable-length array; different from traditional static language int a[4];
let arr: any[] = [1, true, 'Hello'] //any array, can mix various values
// Tuple
let person: [number, string, boolean] = [1, 'Brad', true] //Tuple: array with known number of elements and types; element types need not be the same.
// Tuple Array
let employees: [number, string][] //Array where each element is a tuple
employee = [
[1, 'Brad'],
[2, 'John'],
[3, 'Jill'],
]
// Union
let pid: string | number //Union
/* Below is C language union - a variable that can store several different types of data
union data{
int n;
char ch;
double f;
};
*/
pid = '22'
// Enum
enum Direction1 {
Up = 1,
Down,
Left,
Right,
}
enum Direction2 {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right',
}
2. Map
// Definition
type MapType = {
[id: string]: string;
}
// Instantiation
const map: MapType = {};
map['a'] = 'b';
map['c'] = 'd';
// Deletion
delete map['c'];
// Enumeration
for (let i in map) {
console.log(map[i]);
}
// Get array containing all keys
console.log(Object.keys(map));
// Another implementation using Record
const map: Record<string, string> = {};
map['a'] = 'b';
map['c'] = 'd';
3. Object
// Objects
type User = {
id: number
name: string
}
const user: User = {
id: 1,
name: 'John',
}
// Type Assertion - type casting
let cid: any = 1
// let customerId = <number>cid Casting from any to number
let customerId = cid as number
4. Function
// Functions
function addNum(x: number, y: number): number {
return x + y
}
// Void
function log(message: string | number): void {
console.log(message)
}
5. Interface, Class
// Interfaces
interface UserInterface {
readonly id: number
name: string
age?: number
}
const user1: UserInterface = {
id: 1,
name: 'John',
}
interface MathFunc {
(x: number, y: number): number
}
const add: MathFunc = (x: number, y: number): number => x + y
const sub: MathFunc = (x: number, y: number): number => x - y
interface PersonInterface {
id: number
name: string
register(): string
}
// Classes
class Person implements PersonInterface {
id: number
name: string
constructor(id: number, name: string) {
this.id = id
this.name = name
}
register() {
return `${this.name} is now registered`
}
}
const brad = new Person(1, 'Brad Traversy')
const mike = new Person(2, 'Mike Jordan')
// Subclasses
class Employee extends Person {
position: string
constructor(id: number, name: string, position: string) {
super(id, name)
this.position = position
}
}
const emp = new Employee(3, 'Shawn', 'Developer')
6. Generics
// Generics => Similar to C++ templates
function getArray<T>(items: T[]): T[] {
return new Array().concat(items)
}
let numArray = getArray<number>([1, 2, 3, 4])
let strArray = getArray<string>(['brad', 'John', 'Jill'])
strArray.push(1) // Throws error
7. FAQ
7.1. type alias or interface
- Not much difference; generally prefer using interface
- type is an alias for simple types. Commonly used to give a name to enum types for easier use later. For example:
type ID = number | string;
type ABC = 'a' | 'b' | 'c'
8. d.ts Files
This is similar to header files in C language. They contain type definitions. With these, you can know how to use a JavaScript library in TypeScript. DefinitelyTyped is a header file library maintained by the TypeScript community. Types for third-party JavaScript can all be found there.