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.

User Type Guardを使おう

Last updated at Posted at 2022-03-19

型ガードとは

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;
}
1
0
2

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?