什么';这是';as';typescript中的关键字?
我注意到在TypeScript中声明数组有两种不同的方法。我想知道这是否只是语法上的甜点,还是我缺少了一些底层逻辑?在您的示例中,您在创建变量时告诉编译器变量的类型,并且您演示的两种方式是可互换的。但是,什么';这是';as';typescript中的关键字?,typescript,Typescript,我注意到在TypeScript中声明数组有两种不同的方法。我想知道这是否只是语法上的甜点,还是我缺少了一些底层逻辑?在您的示例中,您在创建变量时告诉编译器变量的类型,并且您演示的两种方式是可互换的。但是,as运算符在代码块中更常用于将变量从一种类型转换为另一种类型,而不是在定义变量时更常用:type格式 使用您的英雄示例的一些伪代码: class Hero { name: string = '' } const heroes: Hero[] = []; const heroes2 = []
as
运算符在代码块中更常用于将变量从一种类型转换为另一种类型,而不是在定义变量时更常用:type
格式
使用您的英雄示例的一些伪代码:
class Hero {
name: string = ''
}
const heroes: Hero[] = [];
const heroes2 = [] as Hero[];
函数X():任意{
return//where是一个我们实际上知道是英雄对象的对象,但由于某些外部原因,它没有或不能在函数定义中声明返回类型
}
函数doStuff(){
如果((X()作为英雄).name=='Bilbo'){
打印(“我们从LOTR中找到了英雄”)
}
}
它们是表达同一事物的两种方式。 在本例中,as关键字用于执行类型断言
function X() : any {
return <something> // where <something> is an object which we actually know to be a Hero object but for some external reason don't or can't declare the return type in the function definition
}
function doStuff() {
if ((X() as Hero).name == 'Bilbo') {
print('We found the hero from LOTR')
}
}
告诉编译器创建heros2数组并将其解释为Hero类型的数组。另一方面
const heroes2 = [] as Hero[];
是显式声明,这是一种规范的方法。最后,这真的是一种语法上的糖分,所以请使用您认为最合适的方式。要注意区别,请查看以下片段:
const heroes: Hero[] = [];
另请参见这是否回答了您的问题?谢谢你的建议。我知道“as”一词是用来指导编译器这个特定数据将是这种类型的。但我的问题是,为什么我们有两种不同的方法来讲述这样的事情?对你来说,这并不重要<代码>英雄:英雄[]=[]只是变量的显式类型注释<代码>[]作为英雄[]是键入空数组的常用方法。断言的类型
Hero[]
将用于推断heroes2
变量的类型。
class Hero {
name: string = ''
}
// `hero` is defined to have type `Hero`. So we get an error on this line,
// because `extra` is not part of `Hero`.
const hero: Hero = {name: '', extra: ''};
// The following definition does not throw error.
// Here, we are casting the object to Hero.
// The object itself conforms to `Hero` type as it contains the necessary properties.
const hero2 = {name: '', extra: ''} as Hero;