Effective Typescript (7)

Jaewoong2·2022년 12월 31일
0

any 타입은 가능한 한 좁은 범위에서만 사용하기

  • any를 사용하지 않을 수 있으면 any를 사용하지 않기

  • 변수의 타입을 any 로 하지말고 딱 사용 범위 에서만 any 로 만들기

type Foo = {
  a: () => string
}
type Bar = {
  b: string
}

function processBar(b: Bar) { /* ... */ }

function funcReturnFoo(): Foo {
  return {
    a: () => ''
  }
}

// 괜찮은 패턴
function func() {
  const x = funcReturnFoo()
  processBar(x as any)
  // const str: string, IDE 에서 x에 대한 속성을 보여줌
  const str = x.a();
}

// 잘못된 패턴
function func2() {
  const x: any = funcReturnFoo()
  processBar(x)
  // const str: any
  // IDE 에서 메소드들 보여주지 않음
  const str = x.a()
}
  • any를 사용하게 된다면, 다른 곳 에 영향을 끼치지 않는 범위 에서 사용 될 수 있도록 any를 사용하자.

  • 사실상 as 또는 타입 지정 사용법 으로서, 타입을 임의로 변경 해야할 때, 다른 타입으로 변경이 예상되나 타입 추론이 이루어지지 않을 때 가장 좁은 범위 내에서 타입 변경을 임의로 시켜주고 (as SomethingType) 다른 곳에 영향을 끼치지 않도록 해야한다.


any를 구체적으로 변형 해서 사용하기

  • any 타입의 값을 그대로 정규식이나 함수에 넣는 것은 권장 되지 않음
function getLengthBad(array: any) { return array.length; } // function getLengthBad(array: any): any

function getLength(array: any[]) { return array.length; } // function getLength(array: any[]): number

getLength(2) // 오류
getLengthBad(2) // 오류체크 못함
  • 해당 예시에서 array 의 타입을 any 가 아닌 any의 배열 any[] 로 정함 으로써 어느정도 좁혀 사용 함으로써 반환 타입을 더욱 구체적으로 할 수 있다.

  • 또한, any를 조금이라도 구체화 해야 매개변수로 오류가 나는 것을 어느정도 방지 해 줄 수있다.

  • 함수의 매개변수가 객체이긴 하지만 값을 알 수 없을때 구체화 하는 방법
    • { [key: string]: any }
      • 속성에 접근 할 수 있음
    • {}
      • 속성에 접근 할 수 없음
    • object
      • 속성에 접근 할 수 없음
type IndexingObejct = { [key: string]: any }
type EmptyObject = {}

function func1(obj: IndexingObejct, key: string) {
  return obj[key]
}

function func2(obj: object, key: string) {
  // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'.
  // No index signature with a parameter of type 'string' was found on type '{}'.(7053)
  // (string type) 의 키값이 object의 속성으로 없어서 오류 발생
  return obj[key]
}

function func3(obj: EmptyObject, key: string) {
  // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'EmptyObject'.
  // No index signature with a parameter of type 'string' was found on type 'EmptyObject'.(7053)
  return obj[key]
}
profile
DFF (Development For Fun)

0개의 댓글