Types

// string
let myName: string = 'Sun';
myName = 27; // 27은 string 타입이 아니므로 error

// number
let myAge: number = 27;
myAge = 'Sun'; // 'Sun'은 number 타입이 아니므로 error

// boolean
let hasHobbies: boolean = false;
hasHobbies = 1; // 1은 boolean 타입이 아니므로 error

// assign types
let myRealAge: number;
myRealAge = 27;
myRealAge = '27'; // '27'은 number 타입이 아니므로 error

// array
let hobbies: any[] = ["Cooking", "Sports"];
hobbies = [100];
hobbies = 100; // 100은 array 타입이 아니므로 error

// tuples
let address: [string, number] = ["Superstreet", 99];

// enum
enum Color {
    Gray, // 0
    Green = 100, // 100
    Blue = 2 // 2
}
let myColor: Color = Color.Blue;
console.log(myColor); // 2

// any
let car: any = "BMW";
console.log(car); // BMW
car = { brand: "BMW", series: 3};
console.log(car); // { brand: "BMW", series: 3}

// functions
function returnMyName(): string {
    let myName: string = 'Sun';
    return myName;
}
console.log(returnMyName()); // Sun

// void
function sayHello(): void {
    console.log("Hello!"); // Hello
}

// argument types
function multiply(value1: number, value2: number): number {
    return value1 * value2;
}
console.log(multiply(2, 'Sun')); // 두번째 매개변수의 타입이 number가 아니므로 error
console.log(multiply(10, 2)); // 20

// function types
let myMultiply: (a: number, b: number) => number;
myMultiply = multiply;
console.log(myMultiply(5, 2)); // 10

// objects
let userData: { name: string, age: number } = {
    name: "Sun",
    age: 27
};

// complex object
let complex: {data: number[], output: (all: boolean) => number[]} = {
    data: [100, 3.99, 10],

    output: function (all: boolean): number[] {
        return this.data;
    }
};

// type alias

type Complex = {data: number[], output: (all: boolean) => number[]};

let complex2: Complex = {
    data: [100, 3.99, 10],

    output: function (all: boolean): number[] {
        return this.data;
    }
};

// union types
let myRealRealAge: number | string = 27;
myRealRealAge = "27";
myRealRealAge = true; // true는 number, string 타입이 모두 아니므로 error

// check types
let finalValue = 30;
if (typeof finalValue == "number") {
    console.log("Final value is a number"); // Final value is a number
}

Exercise

let bankAccount = {
  money: 2000,
  deposit(value) {
    this.money += value;
  }
};

let myself = {
  name: "Sun",
  bankAccount: bankAccount,
  hobbies: ["Sports", "Cooking"]
};

myself.bankAccount.deposit(3000);

console.log(myself);

Solution

type BankAccount = { money: number, deposit: (val: number) => void };

let bankAccount: BankAccount = {
  money: 2000,
  deposit(value: number): void {
    this.money += value;
  }
};

let myself: { name: string, bankAccount: BankAccount, hobbies: string[] } = {
  name: "Sun",
  bankAccount: bankAccount,
  hobbies: ["Sports", "Cooking"]
};

myself.bankAccount.deposit(3000);

console.log(myself);