アサーション関数 (assertion functions)
ユーザー定義の型ガード関数として使われるのはType predicateが主ですが、Assertion functionという方法もあります。
Type predicateはboolean型の戻り値に対して使いましたがこちらは関数が例外を投げるかどうかで判定します。型ガード関数のページで作った関数isDuck()をAssertion functionsで書きかえると次のようになります。
tsfunctionisDuck (animal :Animal ): assertsanimal isDuck {if (walksLikeDuck (animal )) {if (quacksLikeDuck (animal )) {return;}}throw newError ("YOU ARE A FROG!!!");}// ここではquacks()は存在しないProperty 'quacks' does not exist on type 'Animal'.2339Property 'quacks' does not exist on type 'Animal'.animal .(); quacks isDuck (animal );animal .quacks ();
tsfunctionisDuck (animal :Animal ): assertsanimal isDuck {if (walksLikeDuck (animal )) {if (quacksLikeDuck (animal )) {return;}}throw newError ("YOU ARE A FROG!!!");}// ここではquacks()は存在しないProperty 'quacks' does not exist on type 'Animal'.2339Property 'quacks' does not exist on type 'Animal'.animal .(); quacks isDuck (animal );animal .quacks ();
こちらはこの関数が呼ばれた後であればいつでも変数animalはDuck型として解釈されます。