Table of contents 1. Video 2. Final Code 3. Summary In this tutorial Benny shows you simple techniques on how to improve your switch statements . Using the tips and tricks from the video, you will never miss a switch case again. You will also learn how to fix error TS2322 , TS2366 and TS7030 .
Video VIDEO
Errors fixed in the video:
TS2322: Type ‘undefined’ is not assignable to type ‘number’.
TS2366: Function lacks ending return statement and return type does not include ‘undefined’.
TS7030: Not all code paths return a value.
Final Code LoanCalculator.ts 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 export enum LoanTerm { ONE_YEAR = 'ONE_YEAR' , TWO_YEARS = 'TWO_YEARS' , THREE_YEARS = 'THREE_YEARS' , FOUR_YEARS = 'FOUR_YEARS' , FIVE_YEARS = 'FIVE_YEARS' }export interface Loan { term : LoanTerm , type : 'AUTO_LOAN' | 'HOME_LOAN' | 'REFINANCING' }export type InterestRate = 1.75 | 2.96 | 3.5 | 5 ;export function getInterestRate (loan: Loan ): InterestRate { switch (loan.term ) { case LoanTerm .ONE_YEAR : return 1.75 ; case LoanTerm .TWO_YEARS : case LoanTerm .THREE_YEARS : return 2.96 ; case LoanTerm .FOUR_YEARS : return 3.5 ; case LoanTerm .FIVE_YEARS : return 5 ; } }const interestRate = getInterestRate ({term : LoanTerm .ONE_YEAR , type : 'AUTO_LOAN' });
Summary Set noImplicitReturns
to true
in your tsconfig.json
Create a switch case for every valid value Define a custom return type to narrow your function’s return values Create a default
case to handle values that might slip in through using your TypeScript code from JavaScript code Learn TypeScript For Free Whether you're a beginner or an experienced programmer, our free TypeScript course offers tremendous value for all skill levels. Presented by Benny , an experienced instructor and contributor to Visual Studio Code, our course covers everything from the fundamentals of the TypeScript programming language to in-depth explorations for advanced programmers.
You'll gain a solid understanding of the language and its features, setting a strong foundation for your programming journey. Subscribe now!