在 TypeScript 中,用尖括号“ < >”括起一个类意味着什么?

我是 TypeScript 的新手,我非常喜欢它,特别是在 Javascript 中做 OOP 是多么容易。然而,当涉及到使用尖括号的时候,我却被困在了试图弄清楚语义的问题上。

从他们的文档中,我看到了几个例子

interface Counter {
(start: number): string;
interval: number;
reset(): void;
}


function getCounter(): Counter {
let counter = <Counter>function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}

还有

interface Square extends Shape, PenStroke {
sideLength: number;
}
  

let square = <Square>{};

我很难理解这到底是什么意思,或者理解它的方式。

有人能给我解释一下吗?

41506 次浏览

This is called Type Assertion.

You can read about it in Basarat's "TypeScript Deep Dive", or in the official TypeScript handbook.

You can also watch this YouTube video for a nice introduction.

That's called Type Assertion or casting.

These are the same:

let square = <Square>{};
let square = {} as Square;

Example:

interface Props {
x: number;
y: number;
name: string;
}


let a = {};
a.x = 3; // error: Property 'x' does not exist on type `{}`

So you can do:

let a = {} as Props;
a.x = 3;

Or:

let a = <Props> {};

Which will do the same