TypeScript 공부(6)

김희목·2024년 8월 26일
0

패스트캠퍼스

목록 보기
49/53

타입 별칭(Alias)

type TypeA = string
type TypeB = string | number | boolean
type User = {
  name: string
  age: number
  isValied: boolean
} | [string, number, boolean]

const userA: User = {
  name: 'Neo',
  age: 85,
  isValied: true
}
const userB: User = ['Evan', 36, false]

function someFunc(param: TypeB): TypeA {
  switch (typeof param) {
    case 'string':
      return param.toUpperCase()
    case 'number':
      return param.toFixed(2)
    default:
      return 'true'
  }
}
type TypeUser = {
  name: string
  age: number
  isValid: boolean
} // 타입별칭

interface InterfaceUser {
  name: string
  age: number
  isValid: boolean
} // 인터페이스

const heropy: InterfaceUser = {
  name: 'Heropy',
  age: 85,
  isValid: true
}

함수 - 명시적 this

타입스크립트에서 함수를 작성할 때 this 키워드를 사용할 수 있는데 그랬을 때 this 키워드에 타입을 어떻게 명시할 수 있는지에 대한 방법입니다.

interface Cat {
  name: string
  age: number
}

const cat: Cat = {
  name: 'Lucy',
  age: 7
}

function hello(message: string) {
  console.log(`hello ${this.name}, ${message}`)
}

hello.call(cat, 'You are pretty awesome!')

해당 코드에서 결과값을 제대로 출력이 되지만 this 부분에 문제가 발생하는데 해당 내용은 'this'에는 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다. 라고 말해줍니다.

일단 암시적으로 'any'라는 것은 정확하게 어떤 값이 들어올지 모르기 때문에 자동으로 any 타입이 설정이 된다는 것인데, any 타입은 우리가 직접 작성하더라도 되도록 사용하지 않는것을 추천하는데 자동으로 any타입이 포함이 된다는 것은 타입스크립트라는 엄격한 문법을 사용하는 프로그래밍 언어에서는 여러모로 주의해야 되는 개념입니다.

그래서 우리는 this가 무엇인지 제대로 알려줘야 합니다. 그 타입을 명시하는 방법은 매개변수 message 앞에 this: Cat 같이 this의 타입을 인터페이스를 사용해서 명시해주는 방법입니다.

interface Cat {
  name: string
  age: number
}

const cat: Cat = {
  name: 'Lucy',
  age: 7
}

function hello(this: Cat ,message: string) {
  console.log(`hello ${this.name}, ${message}`)
}

hello.call(cat, 'You are pretty awesome!')

0개의 댓글