티스토리 뷰

TypeScript

[TypeScript] Functions

BIBLIYA 2022. 10. 12. 15:04

Call Signatures

type Add = (a: number, b: number) => number;

const add: Add = (a, b) => a + b

 

Overloading

//overloading은 함수가 여러개의 call signatures를 가지고 있을 때 발생

type Add = {
	(a: number, b: number) : number
    (a: number, b: string) : number
}

const add: Add = (a, b) => a + b; //error

const add: Add = (a, b) => {
	if(typeof b === "string") return a
    return a + b 
} 

// 아무 의미 없는 코드
// Nextjs에서 일어나는 overloading

Router.push({
	path: "/home",
    state: 1
})

.push("/home") // overloading => string으로 보낼 수도 있고 object로 보낼 수도 있음

// 해결 방법

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);
} esle {
	console.log(config.path)
}
// 다른 여러개의 argument를 가지고 있을 때 발생

type Add = {
	(a: number, b: number): number
	(a: number, b: number, c: number): number
}

const add: Add = (a,b,c) => {
	return a + b
} // Error

// parameter의 갯수가 다를 때 에러 해결 방법

type Add = {
	(a: number, b: number): number
	(a: number, b: number, c: number): number
}

const add: Add = (a,b,c?: number) => { // optional parameter
	if(c) return a + b + c
	return a + b
}

add(1, 2)
add(1, 2, 3)

Polymorphism

poly - many : several : much : multi

morpho - form : structure

 

타입스크립트에서 함수는 string이나 object를 첫번째 파라미터로 가질 수 있다
// 여러가지 다른 형태

type SuperPrint = {
	(arr: number[]):void
    (arr: boolean[]):void
    //(arr: string[]):void
    //(arr: (number | boolean)[]):void
}

const superPrint: SuperPrint = (arr) => {
	arr.forEach(i => console.log(i))
}

superPrint([1, 2, 3, 4])
superPrint([true, false, true])
superPrint(["a", "b", "c"]) // Error
superPrint([1, 2, true]) // Error

// 타입에 상관없이 사용할 수 있게 해야 함

Generic

// 제네릭 사용으로 타입 정해주기

type SuperPrint = {
	<T>(arr: T[]):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])

// 리턴 타입을 바꾸고 싶은 경우

type SuperPrint = {
	<T>(arr: T[]):T
}

const superPrint: SuperPrint = (arr) => arr[0]

cosnt a = superPrint([1, 2, 3, 4]) // type number
const b = superPrint([true, false, true]) // type boolean
const c = superPrint(["a", "b", "c"]) // type string
const d = superPrint([1, 2, true, "hello"]) // type string | number | boolean

Generics Recap

type SuperPrint = <T, V>(a: T[], b:V):T

const superPrint: SuperPrint = (arr) => arr[0]

cosnt 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, "hello"], [])

Greneric Example

// 함수형
function superPrint<T>(a: T[]) {
	return a[0]
}

cosnt a = superPrint([1, 2, 3, 4]) 
const b = superPrint([true, false, true]) 
const c = superPrint(["a", "b", "c"])
const d = superPrint([1, 2, true, "hello"])


// 제네릭 사용 1
type Person<Extra> = {
	name: string
    extraInfo: Extra
}

const bibliya: Person<{favFood: string}> = {
	name: "bibliya",
    extraInfo: {
    	favFood: "Bulgogi"
    }
}

// 제네릭 사용 1 다른 버전1
type Person<Extra> = {
	name: string
    extraInfo: Extra
}

type userPerson = Person<{favFood: string}>

const bibliya: userPerson = {
	name: "bibliya",
    extraInfo: {
    	favFood: "Bulgogi"
    }
}

// 제네릭 사용 1 다른 버전2 (확장)
type Person<Extra> = {
	name: string
    extraInfo: Extra
}

type UserExtra = {
	favFood: string
}

type UserPerson = Person<UserExtra>

const bibliya: UserPerson = {
	name: "bibliya",
    extraInfo: {
    	favFood: "Bulgogi"
    }
}

// 추가
const jae: Person<null> = {
	name: "jae",
    extraInfo: null
}

 

'TypeScript' 카테고리의 다른 글

[TypeScript] Interface Polymorphism (Generic)  (0) 2022.10.13
[TypeScript] Interface & Type  (0) 2022.10.13
[TypeScript] Classes  (0) 2022.10.12
[TypeScript] 기본 타입 정리  (0) 2022.10.12
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/04   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30
글 보관함