简体   繁体   English

Typescript 类型断言和非 null 检查

[英]Typescript type assertions and non null checks

When we do type assertions, if Typescript knows we cannot be right, it complains.当我们进行类型断言时,如果 Typescript 知道我们不可能正确,它会抱怨。 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:但是当启用非 null 检查时,它不会抱怨没有从 function 返回,就像我们设置了类型一样:

// '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 ?我可以理解 Typescript 在我们使用类型断言时不做任何检查,但是由于它确实做了一些检查(它抱怨在第一个示例中返回一个字符串),为什么它在返回undefined时没有抱怨预期数字和strictNullChecks设置为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 .鉴于 typescript 系统的结构性质,function 类型(start: number) => number(start: number) => void的子类型,因此这意味着您可以断言(start: number) => void实际上是(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.在您的示例中,您应该只将类型注释放在变量上,这将使 typescript 正确检查类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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