- 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.
推薦閱讀
- C++面向對象程序設計(第三版)
- SpringMVC+MyBatis快速開發與項目實戰
- Java高手真經(高級編程卷):Java Web高級開發技術
- 算法大爆炸:面試通關步步為營
- Serverless架構
- Learning ArcGIS for Desktop
- Extending Puppet(Second Edition)
- FPGA Verilog開發實戰指南:基于Intel Cyclone IV(進階篇)
- Python+Tableau數據可視化之美
- Programming with CodeIgniterMVC
- BeagleBone Robotic Projects(Second Edition)
- Mastering Apache Camel
- Swift iOS Programming for Kids
- 大象:Thinking in UML(第二版)
- C++程序設計習題與實驗指導