TypeScript 基礎編 -後編- ~クラスから列挙まで~
キーワード
typeof
typeof
を使用して、宣言済みの変数の型を取得できる。
let asString: string = '' let test: typeof asString test = 'aiueo' //OK test = 0 //NG
keyof
keyof
でLiteral Unionなどのオブジェクトのプロパティ名称を取得できる。
typeof
との併用可能。
アサーション
アサーション(宣言)は値の型について把握している場合に使用。
ダウンキャスト可能な互換性のある場合に「この型である」と宣言する。
<>
とas
を使用する方法がある。
推奨はas
でアサーションを利用すると強力な型付けが可能になる。
let asString: any = 'String now'; let len: number = (<string>asString).length;
let asString: any = 'String now'; let len: number = (asString as string).lentgh;
クラス
宣言と継承
class Hoge{ ... constructor(aiueo: string, kakiku: string){ this.aiueo = aiueo this.kakiku = kakiku } } const hoge = new Hoge(kani , uni)
親クラスを継承したサブクラスで
super関数は親クラスのコンストラクタ実行に相当する。
クラスメンバ修飾子
public``protected``private
が付与できる。
他の言語と同様で
public
はどこでも。
protected
はサブクラスのみ。
private
は同一クラスのみ。
列挙型
列挙型はenum
を使用する。
数値列挙
初期化子を省ける。
enum Direction { aiu, // = 0 eo, // = 1 wa, // = 2 } const aiu = Direction.aiu
文字列挙
初期化しなければいけない。
enum Direcrtion{ aiu = "eo", wa = "on" }
open ended
列挙値の追加が可能。
enum Direction{ aiu = "eo" } enum Direction{ wa = "on" }