这些类型断言或类型转换方法在TypeScript中有什么区别 [英] What are the difference between these type assertion or casting methods in TypeScript

查看:55
本文介绍了这些类型断言或类型转换方法在TypeScript中有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对TypeScript还是很陌生,能否解释一下这些类型断言方法之间的区别:

I'm fairly new with TypeScript, could you explain what are the difference between these methods of type assertion:

// 1. Using :
let myStr: string;

// 2. Using as
let strLength = (myStr as string).length;

// 3. Using <> on left side
let strLength = <string>myStr.length;

// 4. Using <> on right side
let myObs: Observable<number>

以及什么时候使用另一种?谢谢

and when to use one over the others? Thanks

推荐答案

// 1. Using :
let myStr: string;  // declaring a variable with its type as string

// 2. Using as
let strLength = (myStr as string).length; // casting a variable's type to string type using `as` keyword,but here type of strLength is determine by type assertion as there is no explicit type defined.

// 3. Using <> on left side
let strLength = <string>myStr.length;  // same as 2 above but using <>

// 4. Using <> on right side
let myObs: Observable<number>  // Observable is a generic type you can specify its type(T) in  Observable<T>, here it is `number` type.

但是,当使用<>JSX中的样式断言,因此建议使用 as 以获得一致性.

However there is an ambiguity in the language grammar when using <> style assertions in JSX, hence recommended to use as for consistency.

打字稿转换:

https://acdcjunior.github.io/typescript-cast-object-to-other-type-or-instanceof.html

https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html

Typescript通用类型: https://www.typescriptlang.org/docs/handbook/2/generics.html

Typescript generic type : https://www.typescriptlang.org/docs/handbook/2/generics.html

这篇关于这些类型断言或类型转换方法在TypeScript中有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆