我对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>{};

I am having trouble underst和ing what this exactly means or the way to think of/underst和 it.

谁能给我解释一下吗?

推荐答案

这叫做Type Assertion或铸造.

这些都是一样的:

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

这也会起到同样的作用

Typescript相关问答推荐

从接口创建类型安全的嵌套 struct

React-Native运行方法通过监听另一个状态来更新一个状态

如何使用axios在前端显示错误体

typescript抱怨值可以是未定义的,尽管类型没有定义

如何在函数参数中使用(或模仿)`success`的行为?

带占位符的模板文字类型何时扩展另一个?

与字符串文字模板的结果类型匹配的打字脚本

TypeScrip:来自先前参数的参数中的计算(computed)属性名称

Angular:ngx-echart 5.2.2与Angular 9集成错误:NG 8002:无法绑定到选项,因为它不是div的已知属性'

将具有Readonly数组属性的对象接口转换为数组

如何避免从引用<;字符串&>到引用<;字符串|未定义&>;的不安全赋值?

为什么TS2339;TS2339;TS2339:类型A上不存在属性a?

map 未显示控制台未显示任何错误@reaction-google-map/api

作为参数的KeyOf变量的类型

基于泛型的类型脚本修改类型

如何正确键入泛型相对记录值类型?

如何使用useSearchParams保持状态

换行TypeScript';s具有泛型类型的推断数据类型

React-跨组件共享功能的最佳实践

基于参数的 TS 返回类型