TS代码如下:
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
在代码中<Square>{}
表示什么含义
TS代码如下:
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
在代码中<Square>{}
表示什么含义
尖括号内是泛型(参数类型化),在文中是断言类型(ts的另外一种断言是as 关键字),你可以理解为是强制类型转换。{}表示初始化,类似于js中的构造函数区域。如果你有java或golang,C... 哪怕一点点静态语言基础,就很清楚了。换而言之,就是使用零值初始化一个Square接口类型变量,用js的话来说,就是要你给出一个对象,该对象有字符串类型color属性,数字类型sideLength,像下面这样
let square = {color:'白色',sideLength:255}
编译结果
<Square>表示强制类型转换
https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions