diadia

興味があることをやってみる。自分のメモを残しておきます。

typescript 型の判定方法

typescriptは静的型付け言語なので、型を意識さざるを得ない。
例えばユニオン型で2つの異なるクラスを定義した場合、そのインスタンスはクラスによって使えるプロパティが変わる。 ていうことで、型を判定する条件分岐と判定する方法が重要になるらしい。

判定方法: 型の判定方法は3つある。

  • typeof を使う方法
  • instanceofを使う方法
  • inを使う方法

型の判定方法は3つあるが、typeofはtypescriptで作られた型を判定するしかできない。   今回のケースではクラスの型判定を行いたい。このケースでは、typeof は使うことができない。
したがって instanceofまたはinを使うことになる。

const mojiretsu: string = 'wahahaha';
console.log(typeof mojiretsu === 'string');
// true が返る


class Book {
    title: string;
    price: number;
}

class Blog {
    title: string;
    content: string;
}

type ReadingObject = Book | Blog;
let readingObject = new Book();

console.log('price' in readingObject);
// trueが返る

console.log( readingObject instanceof Book);
// trueが返る