[TypeScript] 함수 - 명시적 this 타입, 오버로딩
명시적 this타입
interface Cat {
name: string
age: number
}
const cat:Cat = {
name: 'Lucy',
age: 3
}
function hello(this: Cat, message: string){
console.log(`hello ${this.name}, ${message}`)
}
hello.call(cat, 'you are pretty')
- 함수의 매개변수처럼 this가 Cat 인터페이스를 따르는 객체를 가르킬 것이라 알려주면 this에는 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다라는 메세지는 출력되지 않는다
- 매개변수에 this를 포함시키는 것처럼 포함시키는 것처럼 보이지만 활용되지 않고 단지 문법적 지원으로 보면 된다.
함수의 오버로딩
- 같은 기능을 하지만 매개변수의 개수와 타입이 다른 함수들에 대해 동일한 함수 이름을 허용하는 것을 함수 오버로딩이라고 한다.
- 엄격하게 함수를 선언하면 string 끼리만 더하는 함수와 number 끼리만 더하는 함수를 따로 만들수 있다.
function add(a: string, b: string): string //타입선언
function add(a: number, b: number): number //타입선언
function add(a: any, b: any) { //함수 구현
return a + b
}
add('world', 'hello')
add(1,2)
블로그의 정보
개발 블로그👩💻
Blairj