打字稿中“as”关键字的用途是什么?

nom*_*ail 8 typescript

class Hero {
  name: string = ''
}

const heroes: Hero[] = [];
const heroes2 = [] as Hero[];
Run Code Online (Sandbox Code Playgroud)

我注意到在 TypeScript 中声明数组有两种不同的方法。我想知道这是否只是语法糖,还是我缺少一些潜在的逻辑?

Ian*_*Ash 4

在您的示例中,您在创建变量时告诉编译器变量的类型,并且您演示的两种方法是可以互换的。但是,该运算符更常在代码块中用于将变量从一种类型转换为另一种类型,而不是在更频繁使用as该格式的变量定义期间。:type

使用您的 Hero 示例的一些伪代码:

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')
    }
}
Run Code Online (Sandbox Code Playgroud)

X