✏️ 화살표 함수
let func = (arg1, arg2, ...argN) => expression //아래 함수 표기와 같은 내용임 let func = function(arg1, arg2, ...argN) { return expression; };
function add(a: number, b: number) {
return a + b
}
// 화살표 함수로 나타내면
const add = (a: number, b: number) => a + b
call signature : 함수 위에 마우스를 올렸을 때 보게 되는 것 (밑에 드래그된 부분)
함수의 인자(arguments) 타입 & 리턴 타입을 알려줌
함수를 구현하기 전에 미리 함수의 타입을 지정해놓을 수 있음!
type Add = (a: number, b: number) => number;
const add: Add = (a, b) => a + b; // a와 b의 타입이 number라는 걸 안 알려줘도 됨
// add 함수의 타입이 Add이고, 위에서 Add 타입을 선언해놨기 때문!
type Add = {
(a: number, b: number): number
(a: number, b: string): number
}
const add: Add = (a, b) => {
if(typeof b === "string") return a // b의 타입이 string이면 a(number 타입)를 리턴
return a + b // b의 타입이 string이 아니면 a+b(number 타입)를 리턴
}
type Config = {
path: string,
state: object
}
type Push = {
(path: string): void
(config: Config): void
}
const push: Push = (config) => { // 오버로딩된 함수 내에서 타입을 확인해서 실행함
if (typeof config === "string") { console.log(config)}
else {
console.log(config.path)
}
}
type Add = {
(a: number, b: number): number
(a: number, b: number, c: number): number,
}
const add: Add = (a, b, c?: number) => {
if(c) return a + b + c // c가 있으면 a + b + c를 리턴해라
return a + b // c가 없으면 a + b를 리턴해라
}
console.log(add(1, 2))
console.log(add(1, 2, 3))
🔍 뜻?
many(poly) + structure(morphos)
여러가지 다른 구조, 형태를 가진 함수들..
type SuperPrint = {
(arr: number[]):void
(arr: string[]):void
}
type SuperPrint = {
<TypePlaceholder>(arr: TypePlaceholder[]):void
}
const superPrint : SuperPrint = (arr) => {
arr.forEach(i => console.log(i))
}
superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"])
superPrint([1, 2, true, false])
<T>
, <M>
많이 사용ex) 함수의 몇 번째 인자, 리턴 타입...
type SuperPrint = <T,M>(a: T[], b: M) => T
const superPrint : SuperPrint = (a) => a[0]
const a = superPrint([1, 2, 3, 4],"x")
const b = superPrint([true, false, true], 1)
const c = superPrint(["a", "b", "c"], false)
const d = superPrint([1, 2, true, false, "hello"], [])
function superPrint<T>(a: T[]){
return a[0]
}
const a = superPrint([1, 2, 3, 4])
const b = superPrint([true, false, true])
const c = superPrint(["a", "b", "c"])
const d = superPrint([1, 2, true, false])
type Player<E> = {
name: string
extraInfo: E
}
type NicoExtra = {
favFood: string
}
type NicoPlayer = Player<NicoExtra>
const nico: NicoPlayer = {
name: "Nico",
extraInfo: {
favFood: "kimchi"
}
}
// extraInfo가 없는 경우 제네릭 타입 = null 타입으로 함
const lynn: Player<null> = {
name: "Lynn",
extraInfo: null
}