TIL_21.01.30 ๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ๐Ÿƒ๐Ÿฝโ€โ™‚๏ธ

18294 ๋‹จ์–ด TILTIL

TS

ํด๋กœ์ € JS => TS

const makeCounter = (initialValue) => {
  let count = initialValue;
  const increase = () => {
    return count++;
  }
  return increase;
}
const makeCounter = (initialValue: number): (() => number) => {
  let count = initialValue;
  const increase = (): number => {
    return count++;
  };
  return increase;
};

Defualt parameter

const sum = (a: number, b: number = 2): number => a + b;

console.log(sum(10)); // 12

Indexable type

type KeyValueType = {
  [key: string]: string;
};

const makeObject = (key: string, value: string): KeyValueType => ({
  [key]: value
});

console.log(makeObject("name", "lee")); // {name: "lee"}

Class method

class Person {
  constructor(public name: string) {}
  sayName(): string {
    return this.name;
  }
}

const user1 = new Person("Kim");
console.log(user1.sayName()); // Kim

Method chain

class Person {
  constructor(public name: string, public friends: string[] = []) {}
  sayName(): string {
    return this.name;
  }
  addFriend(friendName: string): this {
    this.friends.push(friendName);
    return this; // this๋ฅผ ๋ฐ˜ํ™˜ํ•ด์„œ metod chaining์ด ๊ฐ€๋Šฅํ•˜๊ฒŒ ๋งŒ๋“ค์–ด์ค€๋‹ค.
  }
}

const user1 = new Person("Kim");
const friends = user1.addFriend("lee").addFriend("choi").addFriend("park")
  .friends;

console.log(friends); // ["lee", "choi", "park"]

Generic

๋ฐฐ์—ด์„ ๋‹ค๋ฃจ๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•  ๋•Œ๋Š” ํƒ€์ž…์ด ๊ณ ์ •๋œ ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค๊ธฐ๋ณด๋‹ค๋Š” ์ œ๋„ˆ๋ฆญ ํƒ€์ž…์„ ์‚ฌ์šฉํ•˜๋Š” ํŽธ๋ฆฌํ•˜๋‹ค.

const arrayLength = <T>(array: T[]) => array.length;

console.log(arrayLength(["str", 2])); // 2

์ œ๋„ˆ๋ฆญ ํ˜•ํƒœ๋กœ ๊ตฌํ˜„๋œ ํ•จ์ˆ˜๋Š” ์›์น™์ ์œผ๋กœ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ํ˜•ํƒœ๋กœ ๋ช…์‹œํ•ด ์ฃผ์–ด์•ผํ•œ๋‹ค. ํ•˜์ง€๋งŒ ์ƒ๋žตํ•ด๋„ ์•Œ์•„์„œ ํƒ€์ž… ์ถ”๋ก ์„ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ƒ๋žต์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

const saySomething = <T>(something: T): T => something;

console.log(saySomething<number>(20));
console.log(saySomething<string>("Hello!"));

Function signature

๋ณ€์ˆ˜์— ํƒ€์ž…์ด ์žˆ๋“ฏ ํ•จ์ˆ˜ ๋˜ํ•œ ํƒ€์ž…์ด ์žˆ๋‹ค. ํ•จ์ˆ˜์˜ ํƒ€์ž…์„ ํ•จ์ˆ˜์˜ ์‹œ๊ทธ๋‹ˆ์ฒ˜๋ผ๊ณ  ํ•œ๋‹ค.

const sum = (a: number): number => a;

const foo: (name: string, age: number) => number = function (
  name: string,
  age: number
): number {
  return age;
};

foo("lee", 20);

type SumFunc = (num1: number, num2: number) => number;

const bar: SumFunc = function (numb1: number, numb2: number): number {
  return numb1 + numb2;
};

์ข‹์€ ์›นํŽ˜์ด์ง€ ์ฆ๊ฒจ์ฐพ๊ธฐ