Assertion function
Type predicate chủ yếu được sử dụng như user-defined type guard function, nhưng cũng có một phương pháp khác là assertion function.
Type predicate được sử dụng với giá trị trả về kiểu boolean, còn assertion function xác định dựa trên việc function có throw exception hay không. Nếu viết lại function isDuck() được tạo trong trang type guard function bằng assertion function, nó sẽ như sau:
tsfunctionisDuck (animal :Animal ): assertsanimal isDuck {if (walksLikeDuck (animal )) {if (quacksLikeDuck (animal )) {return;}}throw newError ("YOU ARE A FROG!!!");}// Ở đây quacks() không tồn tạiProperty '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!!!");}// Ở đây quacks() không tồn tạiProperty 'quacks' does not exist on type 'Animal'.2339Property 'quacks' does not exist on type 'Animal'.animal .(); quacks isDuck (animal );animal .quacks ();
Với cách này, sau khi function được gọi, biến animal sẽ luôn được hiểu là kiểu Duck.