1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【TypeScript】値の型によって条件分岐を行う方法

1
Posted at

値の型によって条件分岐を行う方法を2つ紹介します。

typeofを使った方法

valueがプリミティブ型に限定される場合、typeofを使って条件分岐をすることができます。

const divideByType = (value: string | number) => {
	if (typeof value === "string") {
		return "string型です";
	} else {
		return "number型です";
	}
}

inを使った方法

valueの型がプリミティブ型ではない場合、typeofを使った条件分岐は難しいです。なぜなら、全てobject型と判定されてしまうからです。

この問題を解決するには、inを使います。inを使って一方の型のみが持つプロパティがvalueに存在するかどうかをチェックすることで、型推論を行うことができます。

interface Dog {
	dogType: string;
	name: string;
	age: number;
}

interface Cat {
	catType: string;
	name: string;
	age: number;
}

const divideByType = (value: Dog | Cat) => {
	if ("dogType" in value) {
		return "Dog型です";
	} else {
		return "Cat型です";
	}
}

const test = {
	dogType: "チワワ",
	name: "jun",
	age: 2,
}
const result = divideByType(test); 
console.log(result); // "Dog型です"と出力される

おまけ:ジェネリクスを使ってみる

関数に値を渡す時点でその値の型がわかっているのであれば、引数の型をユニオン型にするのではなく、ジェネリクスを使う方法もあります。

const divideByType = <T>(value: T) => {
	if (typeof value === "string") {
		return "string型です";
	} else {
		return "number型です";
	}
}

const result = divideByType<string>("文字列です");
console.log(result); // "string型です"と出力される

ただし、ジェネリクスを使うとvalueの型がなんでも許容されるため、関数divideByType内の条件分岐が複雑になってしまうことがあります。一長一短ですね。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?