LoginSignup
0
0

More than 5 years have passed since last update.

TypeScript Handbook の Advanced Types をちょっとだけ掘り下げる - その4 String Literal Types / Numeric Literal Types

Last updated at Posted at 2018-08-04

はじめに

本記事は TypeScript HandbookAdvanced Types に書かれているものをベースに、説明されている内容をこういう場合はどうなるのかといったことを付け加えて ちょっとだけ 掘り下げます。完全な翻訳ではなく、若干元の事例を改変しています。
今回は String Literal Types / Numeric Literal Types の二つの節について掘り下げます。

その1 Type Guards and Differentiating Types は こちら
その2 Nullable types は こちら
その3 Type Aliases は こちら
その5 Discriminated Unions は こちら
その6 Index types は こちら
その7 Mapped types は こちら

String Literal Types

文字列リテラル型は、ユニオンやエイリアス、 Type Guard と組み合わせることで enum のような機能を実現することができます。

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 {
      // null か undefined (コンパイラオプションの `--strictNullCheck` が有効な場合、不要)
    }
  }
}

let button = new UIElement();
button.animate(0, 0, 'ease-in');
button.animate(0, 0, 'uneasy'); // コンパイルエラー

Easing という型エイリアスの変数には三つの文字列のいずれかだけを渡すことができ、それ以外の文字列が渡された場合には、エラーが起きます。
Easing に含まれる文字列が返って来るとしても string 型を渡すとエラーになります。

function getEasingString(): string {
  return 'ease-in';
}
function getEasing(): Easing {
  return 'ease-in';
}
button.animate(0, 0, getEasingString()); // コンパイルエラー
button.animate(0, 0, getEasing());       // OK

宣言時に定数を渡すことはできません。

const EASE_IN = 'ease-in';
const EASE_OUT = 'ease-out';
const EASE_IN_OUT = 'ease-in-out';
type Easing = EASE_IN | EASE_OUT | EASE_IN_OUT; // コンパイルエラー : "Cannot find name 'EASE_IN'."

エイリアスを渡すことはできます。

type EASE_IN = 'ease-in';
type EASE_OUT = 'ease-out';
type EASE_IN_OUT = 'ease-in-out';
type Easing = EASE_IN | EASE_OUT | EASE_IN_OUT; // OK

文字列リテラル型はオーバーロード宣言にも利用できます。

function createElement(tagName: 'img'): HTMLImageElement;
function createElement(tagName: 'input'): HTMLInputElement;
// ... さらにオーバーロード ...
function createElement(tagName: string): Element {
  // 処理
}
createElement('img'); // 戻り値は HTMLImageElement として扱われる

Numeric Literal Types

数値リテラル型も同様の機能です。

function rollDice(): 1 | 2 | 3 | 4 | 5 | 6 {
  // ...
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0