Why TSC does not give error when function returns null
or undefined
while function's return type is number
.
//gives error
//Error : A function whose declared type is neither 'void' nor 'any' must return a value.ts(2355)
function add1(a: number, b: number): number {}
// no error
function add2(a: number, b: number): number {
return undefined;
}
// no error
function add3(a: number, b: number): number {
return null;
}
CodePudding user response:
You get no error when Type Checking compiler option strictNullChecks
is off
. Enabling the option will result in Typescript displaying the error for the functions add2
and add3
.
You can read more about it: strictnullchecks-off and strictnullchecks-on
CodePudding user response:
add "strict":true under "compilerOptions" in tsconfig.json file.
CodePudding user response:
as @S.M mentioned above it is caused by strict
flag indeed it is caused by strictNullChecks
flag.
when I set
"strict": true,
or
"strictNullChecks": true,
TSC gives error as what I expect