型ガードとは
TypeScriptで型を宣言する方法はいくつかありますが、コンパイラに型を学習させる方法として型ガードがあります。
例えば、以下のようなコードはコンパイル時にエラーになります。
.ts
class Dog {
run() {}
}
class Fish {
swim() {};
}
const move = (creature: Dog|Fish) => {
// error: Property 'swim' does not exist on type 'Dog | Fish'.
creature.swim();
}
以下のように型をコンパイラに教えてあげることで回避できます。
型を教えることで誤ったプロパティの呼び出しを防いでいます。
.ts
const move = (creature: Dog|Fish) => {
if (creature instanceof Fish) {
creature.swim();
}
}
User Type Guard
上記の例のようにコンパイラへの型情報を提供することもできますが、is
を使ったUser Type Guardを使うこともできます。
こちらの方が型チェックを使いまわすことができ、直感的なコードを書くことができます。
.ts
interface Creature {
name: string
}
class Dog implements Creature {
name = '';
run() {}
}
class Fish implements Creature {
name = '';
swim() {};
}
const move = (creature: Creature) => {
if (isFish(creature)) {
creature.swim();
}
}
// User Type Guard
const isFish = (creature: Creature) : creature is Fish => {
return creature instanceof Fish;
}