- 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.
推薦閱讀
- LabVIEW程序設計基礎與應用
- 程序員面試筆試寶典
- ASP.NET Core 2 and Vue.js
- VMware vSphere 6.7虛擬化架構實戰指南
- 21天學通C++(第6版)
- Citrix XenServer企業運維實戰
- Unity&VR游戲美術設計實戰
- 深度學習原理與PyTorch實戰(第2版)
- Managing Microsoft Hybrid Clouds
- Java Web開發實例大全(基礎卷) (軟件工程師開發大系)
- Java程序設計基礎(第6版)
- AutoCAD基礎教程
- Mastering ASP.NET Web API
- 可視化H5頁面設計與制作:Mugeda標準教程
- IBM DB2 9.7 Advanced Application Developer Cookbook