我对 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;
}
and
interface Square extends Shape, PenStroke {
sideLength: number;
}
let square = <Square>{};
我无法理解这到底意味着什么或思考/理解它的方式。
有人可以向我解释一下吗?
这就是所谓的类型断言 https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions或铸造。
这些是相同的:
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 `{}`
所以你可以这样做:
let a = {} as Props;
a.x = 3;
Or:
let a = <Props> {};
哪个会做同样的事情
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)