개발 일기

Literal Types ? 본문

컴퓨터 언어/Typescript

Literal Types ?

이건욱

String Literal Types ?

// We're making a guarantee that this variable
// helloWorld will never change, by using const.

// So, TypeScript sets the type to be "Hello World" not string
const helloWorld = "Hello World";

// On the other hand, a let can change, and so the compiler declares it a string
let hiWorld = "Hi World";

다음과 같은 Literal Types는 Primitive Type의 하위 타입입니다.

따라서 Primitive Type 보다 Literal Types을 사용을 할때 더 제한적으로 설정 할수가 있습니다.

 

type Easing = "ease-in" | "ease-out" | "ease-in-out";

class UIElement {
  animate(dx: number, dy: number, easing: Easing) {
    if (easing === "ease-in") {
      // ...
    } else if (easing === "ease-out") {
    } else if (easing === "ease-in-out") {
    } else {
      // It's possible that someone could reach this
      // by ignoring your types though.
    }
  }
}

let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy");

따라서 위와 같이 Easing type이 uneasy가 없기 때문에 (ease-in , ease-out , ease-in-out) 외에 값들은 에러가 발생합니다.

 

함수에서도 Literal Type으로 다음과 같이 구별할수가 있습니다.

function createElement(tagName: "img"): HTMLImageElement;
function createElement(tagName: "input"): HTMLInputElement;
// ... more overloads ...
function createElement(tagName: string): Element {
  // ... code goes here ...
}

Number Literal Types ?

보통적으로 다음과 같이 사용이 가능합니다.

interface MapConfig {
  lng: number;
  lat: number;
  tileSize: 8 | 16 | 32;
}

setupMap({ lng: -73.935242, lat: 40.73061, tileSize: 16 });

'컴퓨터 언어 > Typescript' 카테고리의 다른 글

Enums ?  (0) 2020.05.12
Unions and Intersection Types ?  (0) 2020.05.10
Function ?  (0) 2020.05.03
Class ?  (0) 2020.05.01
Interface ?  (0) 2020.04.30
Comments