简体   繁体   中英

Typescript type assertions and non null checks

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM