用尖括号“<>"将类括起来是什么意思?在打字稿中是什么意思? [英] What does enclosing a class in angle brackets "<>" mean in TypeScript?
本文介绍了用尖括号“<>"将类括起来是什么意思?在打字稿中是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对 TypeScript 非常陌生,我非常喜欢它,尤其是在 Javascript 中执行 OOP 是多么容易.然而,在使用尖括号时,我一直试图弄清楚语义.
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.
从他们的文档中,我看到了几个像
From their docs, I have seen several examples 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;
}
和
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.
谁能给我解释一下?
推荐答案
这就是所谓的 输入断言 或强制转换.
That's called Type Assertion or casting.
这些都是一样的:
let square = <Square>{};
let square = {} as Square;
示例:
interface Props {
x: number;
y: number;
name: string;
}
let a = {};
a.x = 3; // error: Property 'x' does not exist on type `{}`
所以你可以这样做:
let a = {} as Props;
a.x = 3;
或者:
let a = <Props> {};
哪个会做同样的
这篇关于用尖括号“<>"将类括起来是什么意思?在打字稿中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文