- Learn React with TypeScript 3
- Carl Rippon
- 141字
- 2021-06-10 19:16:38
--noImplicitReturns
This ensures we return a value in all branches of a function if the return type isn't void.
Let's see this in action with an example:
- In our OrderDetail class, let's say we have the following implementation for our getTotal method:
getTotal(discount: number): number {
if (discount) {
const priceWithoutDiscount = this.product.unitPrice * this.quantity;
const discountAmount = priceWithoutDiscount * discount;
return priceWithoutDiscount - discountAmount;
} else {
// We forgot about this branch!
}
}
- We've forgotten to implement the branch of code that deals with the case where there is no discount. If we compile the code without the --noImplicitReturns flag, it compiles fine:
tsc orderDetail
- However, let's see what happens if we compile the code with the --noImplicitReturns flag:
tsc orderDetail --noImplicitReturns
We get the following error, as expected:
orderDetail.ts(9,31): error TS7030: Not all code paths return a value.
推薦閱讀
- Fundamentals of Linux
- Mastering Adobe Captivate 2017(Fourth Edition)
- PHP程序設計(慕課版)
- 控糖控脂健康餐
- Web Scraping with Python
- C語言程序設計基礎與實驗指導
- 程序員面試算法寶典
- Windows Server 2012 Unified Remote Access Planning and Deployment
- INSTANT Sinatra Starter
- Python Essentials
- Geospatial Development By Example with Python
- Citrix XenServer企業運維實戰
- 零代碼實戰:企業級應用搭建與案例詳解
- 創意UI Photoshop玩轉移動UI設計
- Hacking Android