TIL_21.01.30 ๐๐ฝโโ๏ธ๐๐ฝโโ๏ธ
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;
};
Author And Source
์ด ๋ฌธ์ ์ ๊ดํ์ฌ(TIL_21.01.30 ๐๐ฝโโ๏ธ๐๐ฝโโ๏ธ), ์ฐ๋ฆฌ๋ ์ด๊ณณ์์ ๋ ๋ง์ ์๋ฃ๋ฅผ ๋ฐ๊ฒฌํ๊ณ ๋งํฌ๋ฅผ ํด๋ฆญํ์ฌ ๋ณด์๋ค https://velog.io/@kdo0129/TIL21.01.30์ ์ ๊ท์: ์์์ ์ ๋ณด๊ฐ ์์์ URL์ ํฌํจ๋์ด ์์ผ๋ฉฐ ์ ์๊ถ์ ์์์ ์์ ์ ๋๋ค.
์ฐ์ํ ๊ฐ๋ฐ์ ์ฝํ ์ธ ๋ฐ๊ฒฌ์ ์ ๋ (Collection and Share based on the CC Protocol.)
์ข์ ์นํ์ด์ง ์ฆ๊ฒจ์ฐพ๊ธฐ
๊ฐ๋ฐ์ ์ฐ์ ์ฌ์ดํธ ์์ง
๊ฐ๋ฐ์๊ฐ ์์์ผ ํ ํ์ ์ฌ์ดํธ 100์ ์ถ์ฒ ์ฐ๋ฆฌ๋ ๋น์ ์ ์ํด 100๊ฐ์ ์์ฃผ ์ฌ์ฉํ๋ ๊ฐ๋ฐ์ ํ์ต ์ฌ์ดํธ๋ฅผ ์ ๋ฆฌํ์ต๋๋ค