TypeScript: a Quick Guide by Example

// typescript is an open source language and is a superset of javascript;
// this means that all javascript code is typescript code so using types is entirely optional;
// types from 3rd parties can be added with type declarations, e.g. npm i @types/<lib> -D

// typescript will make your code more verbose via type definitions;
// the benefits of this are: you'll catch more bugs and maintain more team-oriented code
// as your peers won't have your familiarity

// setup: npm i -g typescript
// to ensure install worked, get the version: tsc -v

// to configure typescript, you need to create a "tsconfig.json" file;
// you can do this yourself and input directives manually, or you can
// run "tsc --init" to pre-populate the file with default directives 
// that you can change

// within the "tsconfig.json," file change the following directives to suit your environment:
// "outDir": "./dist"
// "rootDir": "./src"

// 1. primitives:

let id: number = 1;
let company: string = "a company name here";
let isOpen: boolean = true;
let x: any = "default for variables not type-scoped; any value can appear here";

// 2. arrays:

let ids: number[] = [1,2,3,4,5]; // an array of only numbers
let arr: any[] = [1, true, "a string"]; // all valid values b/c this is an array of the "any" value

// 3. tuples:

let person: [number, string, boolean] = [1, 'a string', true];

let employee: [number, string][];

employee = [
    [1, 'charles'],
    [2, 'bill'],
]

// 4. unions:

let pid: string | number;

pid = 1;
pid = '1z';

// 5. enums:

// by default, Up = 0; Down = 1; Left = 2; Right = 3
enum Direction1 {
    Up,
    Down,
    Left,
    Right
};

console.log(Direction1.Up); // will echo 0

enum Direction2 {
    Up = 27,
    Down,
    Left,
    Right
};

console.log(Direction2.Up); // will echo 27
console.log(Direction2.Left); // will echo 29

// 6. objects:

const user1: { id: number, name: string } = {
    id: 1,
    name: "michael",
}

type User = {
    id: number,
    name: string,
}

const user2: User = {
    id: 2,
    name: 'timothy',
}

// 7. type assertions:

let cid: any = 1;
let customerId = <number>cid;
// or, another format: let customerId = cid as number;

console.log(customerId); // if cid is initialized as !number, no error is shown; however, you can't change customerId to a new value that's not a number

// 8. functions:

function addNum(x: number, y: number): number {
    return x + y;
}

console.log(addNum(1, 2));

function log(message: string | number): void {
    console.log(message);
}

log('hello');

// 9. interfaces:

// interfaces and types are nearly identical;
// an interface doesn't support unions whereas a type does
// e.g., type Point = number | string -- valid
// e.g., interface Point = number | string -- invalid

interface PatientInterface {
    id: number;
    name: string;
}

const patient1: PatientInterface = {
    id: 1,
    name: 'john',
}

interface DoctorInterface {
    id: number;
    readonly name: string;
    speciality?: string; // this is an optional property
    [propName: string]: any; // not necessary here; but an example of how to capture other property names injected from other sources
}

const doctor1: DoctorInterface = {
    id: 1,
    name: 'michael',
}

doctor1.id = 2;
// doctor1.name = "johnny"; // error b/c of readonly property above

// 10. function interfaces:

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;

// 11. classes:

// classes have been in the javascript language since es6 (es2015)

interface PersonInterface {
    id: number;    
    readonly name: string;    
    register(): string;
}

class Person implements PersonInterface {
    id: number;     
    readonly name: string;    

    // private and protected are available descriptors for properties when the class isn't using an interface

    constructor(id: number, name: string) {
        this.id = id;        
        this.name = name;        
    }

    register() {
        return `${this.name} is now registered`
    }
}

const brad = new Person(1, 'brad');
const mike = new Person(2, 'mike');

console.log(brad, mike);

brad.id = 5;

console.log(brad.register());

// 12. subclasses:

class Employee extends Person {
    position: string;

    constructor(id: number, name: string, position: string) {
        super(id, name)
        this.position = position;
    }
}

const charles = new Employee(3, 'charles', 'programmer');

console.log(charles.register());

// 13. generics:

// used to build reusable components

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', 'charles']);

// numArray.push('hello'); // error b/c generic is a number type

numArray.push(5);

// 14. typescript with react:

// create a react app with typescript in the current folder: npx create-react-app . --template typescript
// npm start

// export interface Props {
//     title: string;
//     color?: string; // the "?" makes color optional
// }

// const Header = (props: Props) => {
//     return (
//         <header>
//             <h1 style={{ color: props.color ? props.color : 'blue' }}>
//                 {props.title}
//             </h1>
//         </header>
//     )
// }

// export default Header;

// transpile typescript to javascript: tsc <filename>.ts
// this creates a <filename>.js file, which you can execute in a browser or with node, e.g. node <filename>.js

If you’re interested in Typescript naming conventions check out the TypeScript Style Guide.

TypeScript Crash Course (Video)