LoginSignup
0
0

More than 1 year has passed since last update.

TypeScript : ユニオン型

Posted at

ユニオン型

ユニオン型とは、A型またはB型として表現できる型。
複数の型に使用することができる。

基本的な使い方

// ユニオン型で定義
type StringNumber = string | number;

// StringNumber型は、文字列と数値の両方を含むことができる
const StrObj: StringNumber = "abcdefghi";
const NumObj: StringNumber = 123456789;

// どちらの型も出力出来る
console.log("StrObj type is " + typeof StrObj + " : " + StrObj);
console.log("NumObj type is "+typeof NumObj + " : " + NumObj);

複数で使う場合

// 複数の型を定義
type Tiger = {
    tigerSound: string;
};
type Gorilla = {
    gorillaSound: string;
};
type Crow = {
    crowSound: string;
};
type Pig = {
    pigSound: string;
};

// 複数の型をUnion型にまとめて、Animal型とする
type Animal = Tiger | Gorilla | Crow | Pig;

// Animal型に複数の型を定義することができる
const tigerObj: Animal = {
    tigerSound: "Roar !"
};
const gorillaObj: Animal = {
    gorillaSound: "Ooh ooh !"
};
const crowObj: Animal = {
    crowSound: "Caw caw"
};
const pigObj: Animal = {
    pigSound: "Oink oink"
};

// Animal型の各値は、それぞれの値を含んでいる
console.log("Tiger sound is " + tigerObj.tigerSound);
console.log("Gorilla sound is " + gorillaObj.gorillaSound);
console.log("Crow sound is " + crowObj.crowSound);
console.log("Pig sound is " + pigObj.pigSound);

出力サンプル

$ npx tsc
$ node dist/index.js
StrObj type is string : abcdefghi
NumObj type is number : 123456789

Tiger sound is Roar !
Gorilla sound is Ooh ooh !
Crow sound is Caw caw
Pig sound is Oink oink

Node.js

TypeScript をコンパイルして実行するために Node.js をインストール。

https://nodejs.org/en/
note : 安定板である偶数番がオススメ

バージョンチェック
$ node -v

GitHub

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