在 TypeScript 中,将类括在尖括号“<>”中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38831342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:43:45  来源:igfitidea点击:

What does enclosing a class in angle brackets "<>" mean in TypeScript?

typescriptbrackets

提问by davejoem

I am very new to TypeScript and I am loving it a lot, especially how easy it is to do OOP in Javascript. I am however stuck on trying to figure out the semantics when it comes to using angle brackets.

我对 TypeScript 非常陌生,我非常喜欢它,尤其是在 Javascript 中执行 OOP 是多么容易。然而,当涉及到使用尖括号时,我一直试图弄清楚语义。

From their docs, I have seen several example like

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

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;
}

and

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

let square = <Square>{};

I am having trouble understanding what this exactly means or the way to think of/understand it.

我无法理解这究竟意味着什么或思考/理解它的方式。

Could someone please explain it to me?

有人可以向我解释一下吗?

回答by Nitzan Tomer

That's called Type Assertionor 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

哪个会做同样的事情