이팩티브 타입스크립트 ~ item 11

이수빈·2025년 4월 16일
0

Typescript

목록 보기
17/17
post-thumbnail

변수의 명시적 선언

  • 변수를 선언할 때 명시적으로 type 선언을 해주는게 좋다.

  • 정확히 어디서 에러가 났는지 알려주기 때문

const states = [
    {
        name : 'A',
        capitol : 'a',
    },
    {
        name : 'B',
        capitol : 'b',
    },
]

for (const state of states){
    console.log(state.capital) // 에러 capital 속성이 없음 =>  states에서 오타가 났는데
}
  • 해당 states를 명시적으로 타입 선언하면 문제는 해결된다.
type state = {
    name : string
    capital : string
}

const states:state[] = [
    {
        name : 'A',
        capitol : 'a', //capital을 의도한게 아닌지하고 에러출력
    },
    {
        name : 'B',
        capitol : 'b',
    },
]

for (const state of states){
    console.log(state.capital)
}

TS config 설정

  • noImplicitAny : 변수들이 미리 정의된 타입을 가져아함. (any 불가)
  • strictNullChecks : null, undefined가 모든 타입에서 허용되는지 확인
  • 두개를 포함하는 설정이 strict 설정
const x:number = null; // strictNullChecks해제시 가능

const x:number = null; // strictNullChecks체크시 에러
  • TS 컴파일러의 두가지 역할 => 각각을 독립적으로 수행한다.

      1. 최신 TS,JS를 브라우저에서 동작 할 수 있도록 구버전의 JS로 트랜스파일하는 역할(바벨)
      1. 코드의 타입오류 체크함.
  • 그렇기 때문에 타입오류가 있어도 => 빌드가 가능

  • 만약 오류가 있을 때 컴파일하지 않으려면 => noEmitOnError 옵션 설정하면 됨

런타임시 타입체크 ?

  • Rectangle은 형식만 참조하지만 여기서는 값으로 사용되고 있습니다. => TS가 JS로 컴파일되는 과정에서 모든 타입, 인터페이스는 제거됨.
interface Square {
  width: number;
}
interface Rectangle extends Square {
  height: number;
}
type Shape = Square | Rectangle;

function calculateArea(shape: Shape) {
  if (shape instanceof Rectangle) {
    //                 ~~~~~~~~~ 'Rectangle' only refers to a type,
    //                           but is being used as a value here
    return shape.height * shape.width;
    //           ~~~~~~ Property 'height' does not exist on type 'Shape'
  } else {
    return shape.width * shape.width;
  }
}
  • 1.속성값으로 분류한다.(속성의 존재여부에 따라 타입을 분류함)
function calculateArea(shape: Shape) {
  if ('height' in shape) {
    return shape.width * shape.height;
    //     ^? (parameter) shape: Rectangle
  } else {
    return shape.width * shape.width;
  }
}
  • 2.런타임에 접근가능한 명시적인 타입정보를 지정한다.(태그기법)
interface Square {
  kind: 'square';
  width: number;
}
interface Rectangle {
  kind: 'rectangle';
  height: number;
  width: number;
}
type Shape = Square | Rectangle;

function calculateArea(shape: Shape) {
  if (shape.kind === 'rectangle') {
    return shape.width * shape.height;
    //     ^? (parameter) shape: Rectangle
  } else {
    return shape.width * shape.width;
    //     ^? (parameter) shape: Square
  }
}
  • 3.Class사용 => 인터페이스는 타입으로만 사용가능하지만, Class는 타입과 값으로 모두 사용가능함.
class Square {
  width: number;
  constructor(width: number) {
    this.width = width;
  }
}
class Rectangle extends Square {
  height: number;
  constructor(width: number, height: number) {
    super(width);
    this.height = height;
  }
}
type Shape = Square | Rectangle;

function calculateArea(shape: Shape) {
  if (shape instanceof Rectangle) {
    return shape.width * shape.height;
    //     ^? (parameter) shape: Rectangle
  } else {
    return shape.width * shape.width;
    //     ^? (parameter) shape: Square
  }
}

객체 레퍼타입을 피하자

  • String 대신 string, Number 대신 number 사용하기 (primitive type사용하자)

function isGreeting(phrase: String) {
  return ['hello', 'good day'].includes(phrase);
  //                                    ~~~~~~
  // Argument of type 'String' is not assignable to parameter of type 'string'.
  // 'string' is a primitive, but 'String' is a wrapper object.
  // Prefer using 'string' when possible.
}

잉여속성체크?

  • 타입이 명시된 변수에 객체리터럴을 할당할 때 => 타입스크립트는 해당 타입의 속성이 있는지, 그리고 그 외의 속성이 없는지 확인한다.

  • 아래는 타입에러이다. => Room에 명시되지 않은 잉여속성이 있기 때문(명시적으로 지정함으로써 잉여속성 검사를 함)

interface Room {
  numDoors: number;
  ceilingHeightFt: number;
}
const r: Room = {
  numDoors: 1,
  ceilingHeightFt: 10,
  elephant: 'present',
// ~~~~~~~ Object literal may only specify known properties,
//         and 'elephant' does not exist in type 'Room'
};
  • 아래코드는 정상 동작한다. => obj자체는 Room 형식이 할당 가능하기 때문. (따로 잉여속성 검사를 하지 않았다)
const obj = {
  numDoors: 1,
  ceilingHeightFt: 10,
  elephant: 'present',
};
const r: Room = obj;  // OK
profile
응애 나 애기 개발자

0개의 댓글