TIL_21.01.30 πŸƒπŸ½β€β™‚οΈπŸƒπŸ½β€β™‚οΈ

Doum KimΒ·2021λ…„ 1μ›” 30일
0

TIL

λͺ©λ‘ 보기
71/71
post-thumbnail

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;
};

0개의 λŒ“κΈ€