#100DAYSOFCODE Day98

#100DAYSOFCODE Day98

Learn about TypeScript

Types by Inference #

let helloWorld = "Hello World";

Defining Types

You can explicitly describe this object’s shape using an interface declaration:

interface User {
  name: string;
  id: number;
}
const user: User = {
  name: "Hayes",
  id: 0,
};

Since JavaScript supports classes and object-oriented programming, so does TypeScript. You can use an interface declaration with classes:

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

class UserAccount {
  name: string;
  id: number;

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

const user: User = new UserAccount("Murphy", 1);

Composing Types

With TypeScript, you can create complex types by combining simple ones. There are two popular ways to do so: with Unions, and with Generics.

Unions

type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

function getLength(obj: string | string[]) {
  return obj.length;
}

Screen Shot 2021-06-09 at 2.22.59 AM.png

Generics

To be continued...