새소식

프론트엔드/typescript

함수 - 명시적 this 타입

  • -

안녕하세요 lika-7입니다

이번 시간에는 TypeScript의 함수 작성에 this 키워드 명시 방법에 대하여 정리 하겠습니다

명시적 this란

💡
함수나 메서드 내에서 this 키워드가 어떤 객체를 가리키는지를 명시적으로 지정하는 것을의미합니다
JavaScript에서 this는 실행 컨텍스트에 따라 동적으로 결정되기 때문에 때로는 예측하기 어려울 수 있습니다 그러나 TypeScript에서는 명시적으로 this를 사용하여 코드를 더 예측 가능하게 만들 수 있습니다.

명시적 this를 사용하는 주요 방법

//TypeScript

interface Cat {
    name: string
    age: number
}

const cat:Cat= {
    name: 'Lay',
    age: 25
}

function hello(message: string){
    console.log(`Hello ${this.name}, ${message}`)
}
hello.call(cat, 'You are pretty awesome!')

위의 코드상에서

console.log(`Hello ${this.name}, ${message}`)

부분중 this.name이 에러가 납니다

this 부분이 타입이 지정되어 있지 않으면 암시적으로 any 타입이 적용된다고 합니다

이러한 내용은 엄격한 문법을 위해 사용하는 typescript에서 주의해야 합니다

일반함수에서 정의

//TypeScript

interface Cat {
    name: string
    age: number
}

const cat:Cat= {
    name: 'Lay',
    age: 25
}

function hello(this:Cat, message: string){
    console.log(`Hello ${this.name}, ${message}`)
}
hello.call(cat, 'You are pretty awesome!')
일반 함수에서 this 키워드는 호출되는 위치에서 정의 됩니다
this:Cat은 매개 변수가 아니라 this: Cat을 명시한 typescript의 문법적 요소 입니다

화살표함수에서 정의

//TypeScript

interface Cat {
    name: string;
    age: number;
}

const cat: Cat = {
    name: 'Lay',
    age: 25
}

const hello = (message: string) => {
    console.log(`Hello ${cat.name}, ${message}`);
}
hello('You are pretty awesome!');
화살표 함수는 자체적으로 this를 바인딩하지 않기 때문에, 함수 내부에서 this를 사용하지 않고 외부 변수 ‘cat’을 직접참조하도록 변결 할 수 있습니다. 명시적으로 this를 전달할 필요가 없습니다

'프론트엔드 > typescript' 카테고리의 다른 글

클래스와 접근 제어자  (0) 2023.09.19
함수 - 오버로딩  (0) 2023.09.19
객체 데이터 타입 지정  (0) 2023.09.19
타입별칭  (0) 2023.09.19
Interface - 확장(상속)  (0) 2023.09.18
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.