TypeScript 3.4: const assertion

Typescript 3.4에 추가된 기능입니다.

const assertion을 사용하면 마치 const 로 선언된 변수 처럼 타입을 고정할 수 있습니다.

const a = 'hello';        // "hello" type
let b = 'hello';          // string type
let c = 'hello' as const; // "hello" type!

c = 'hi' // Error

객체의 경우

하나의 속성에 대한 경우

모든 속성에 대한 경우

discriminated union

유니온 식별을 위한 기능에 유용하게 사용 될 수 있습니다.

const circle = {
  type: 'circle',
  radius: 10
};
const square = {
  type: 'square',
  width: 10,
  height: 20
};
type Shape = typeof circle | typeof square;
function draw(shape: Shape) {
  switch (shape.type) {
    case 'circle':
      console.log(shape.radius); // Error
      break;
    case 'square':
      console.log(shape.width);  // Errir
      break;
  }
}