Effective Typescript

Jaewoong2·2022년 12월 24일
0

상수 객체는 명시적으로 type 을 설정해야 좋다.

  • 의도를 분명하게 하기 위함
    • 근데 타입 추론 이 되는데, 타입 추론을 쓰는게 더 좋을지 type 설정해서 쓰는게 좋을지 잘 모르겠음

암시적 Any 는 허용하지 않는게 좋음

"noImplicitAny": true

const add = (a, b) => a + b  // 오류
const add = (a: number, b: number) => a + b // 정상

타입스크립트는 컴파일에 영향을 주지 않는다.

런타임 때에는 타입 체크가 불가능하다

interface Square {
  width: number;
}

interface Rectangle extends Square {
  height: number;
}

type Shape = Square | Rectangle;

function calculateArea(shape: Shape) {
  if (shape instanceof Rectangle) { // 'Rectangle' 은 형식만 참조, 여기서는 값으로만 사용 되고 있습니다
    return shape.width * shape.height; // 'Shape' 형식에 'height' 속성이 없습니다
  }
  
  return shape.width * shape.width;
} 
  • 태그 기법으로 해결 가능하다.
  • type guard
interface Square {
  kind: 'square';
  width: number;
}

interface Rectangle extends Square {
  kind: 'rectangle';
  height: number;
}

type Shape = Square | Rectangle;

function calculateArea(shape: Shape) {
  if (shape.kind === 'rectangle') { 
    return shape.width * shape.height; 
  }
  
  return shape.width * shape.width;
} 
  • 또는, Class 로 만들게 되면 Type 으로 사용 되거나 Value 로 모두 사용 될 수 있기 때문에 런타임시 접근이 가능해서 오류 없이 코드 작성이 가능하다.
profile
DFF (Development For Fun)

0개의 댓글