Reputation: 1066
When we do type assertions, if Typescript knows we cannot be right, it complains. For instance
type Counter = (start: number) => number;
let counterProblemDetected = ((start: number) => "yo") as Counter;
But when non null checks are enabled, it does not complain about not returning from the function, as it would if we had set the type:
// 'strictNullChecks' is on
// Typescript does not complain
let counterProblemNotDetected = ((start: number) => {}) as Counter;
// Typescript complains about 'void' not being assignable to type number
let counterProblemDetected: Counter = ((start: number) => {})
I don't get the logic behind this. I could understand that Typescript does not do any check when we use type assertions, but since it does do some checks (it complains about returning a string in the first example), why does it not complain when returning undefined
when a number is expected and strictNullChecks
set to true
?
Upvotes: 0
Views: 890
Reputation: 250236
Type assertions are allowed when you are down-casting (ie. you are casting a base type to a subtype). Given the structural nature of the typescript system, the function type (start: number) => number
is a subtype of (start: number) => void
, so this means you can assert that (start: number) => void
is actually (start: number) => number
.
As mentioned in comments it's best to avoid type assertions unless you have a very good reason to use a type assertion (for example the compiler can't figure out something you know to be true). In your examples you should just put the type annotation on the variable, this will make typescript check the type correctly.
Upvotes: 3