TypeScript에서의 this
interface Cat {
name: string
age: number
}
const cat:Cat = {
name: 'Lucy',
age: 1
}
function hello(this: Cat, message:string) {
console.log(`hello ${this.name}, ${message}`)
}
hello.call(cat, 'you are pretty awesome!')
일반 함수에서의 this는 호출 위치에서 정의가 된다. 위 코드에서 this는 call 메서드 속 cat 객체 데이터를 기준으로 호출하고 있다.
이런 경우에, this 타입을 지정해줄 수 있다. 매개변수처럼 보일 수 있으나 함수 내부에서 사용할 수 있는 this 키워드의 타입을 지정해주는 것이기 때문에 매개변수라기보다는 this의 타입을 정해주는 하나의 문법으로 보는 게 좋다.
'TYPESCRIPT' 카테고리의 다른 글
[Typescript] 클래스와 접근제어자 (0) | 2023.12.12 |
---|---|
[Typescript] 함수 오버로딩 (Overloading) (0) | 2023.12.12 |
[Typescript] 타입 별칭(Type Alias) (0) | 2023.12.12 |
[Typescript] 인터페이스 (interface) (0) | 2023.12.04 |
[Typescript] 타입 가드(type guard) (0) | 2023.12.04 |
TypeScript에서의 this
interface Cat {
name: string
age: number
}
const cat:Cat = {
name: 'Lucy',
age: 1
}
function hello(this: Cat, message:string) {
console.log(`hello ${this.name}, ${message}`)
}
hello.call(cat, 'you are pretty awesome!')
일반 함수에서의 this는 호출 위치에서 정의가 된다. 위 코드에서 this는 call 메서드 속 cat 객체 데이터를 기준으로 호출하고 있다.
이런 경우에, this 타입을 지정해줄 수 있다. 매개변수처럼 보일 수 있으나 함수 내부에서 사용할 수 있는 this 키워드의 타입을 지정해주는 것이기 때문에 매개변수라기보다는 this의 타입을 정해주는 하나의 문법으로 보는 게 좋다.
'TYPESCRIPT' 카테고리의 다른 글
[Typescript] 클래스와 접근제어자 (0) | 2023.12.12 |
---|---|
[Typescript] 함수 오버로딩 (Overloading) (0) | 2023.12.12 |
[Typescript] 타입 별칭(Type Alias) (0) | 2023.12.12 |
[Typescript] 인터페이스 (interface) (0) | 2023.12.04 |
[Typescript] 타입 가드(type guard) (0) | 2023.12.04 |