前提
偶然看到了如下代码:
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter =<Counter>function (start: number) { console.log("开始了"); };
counter.interval = 123;
counter.reset = function () { console.log("结束了");};
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
问题:代码中的尖括号"<>"有什么用处呢??
我翻过文档,没有相关说明。
网上普遍说的关于尖括号在ts中的作用:
1、类型断言
var str = '1'
var str2:number = <number> str //str、str2 是 string 类型 将会报错
var str3:number = <number> <any> str //不会报错
console.log(str2)
2、泛型的使用泛型接口、泛型函数等等
但是都没有这种类型的写法
直接在代码块前面添加尖括号里面填写对应接口名
let counter =<Counter>function (start: number) { console.log("开始了"); };
我猜测过:
1、可能类型判断的作用,我尝试了再次添加一对尖括号<>
let counter =<Counter><number>function (start: number) { console.log("开始了"); };
script.ts(8,18): error TS2352: Conversion of type 'number' to type 'Counter' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
script.ts(8,27): error TS2352: Conversion of type '(start: number) => void' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
毫无疑问报错了
2、可能是一种申明告诉编译器这是的接口的函数
于是我弄了一个Counter2然后再使用&连接。
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
interface Counter2 {
interval2: number;
}
function getCounter(): Counter & Counter2 {
let counter =<Counter>function (start: number) { console.log("开始了"); };
counter.interval = 123;
counter.reset = function () { console.log("结束了");};
let counter2 =<Counter2>{ interval2: number=2;console.log("success!!!"); };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
结果肯定错了
3、我把删除
结果肯定报错。如果删除了,怎么知道使用的是哪个接口呢?
最后
我想了想:这个是必须的,删了他不行,非他不可。这奇怪,只要加上了尖括号似乎就可以对接口进行实现了
function getCounter(): Counter {
let counter =<Counter>function (start: number) { console.log("开始了"); };//只要加上了尖括号,似乎就已经获取了接口的引用,从而对接口进行实现操作相当于class counter implements Counter {}一样
counter.interval = 123;
counter.reset = function () { console.log("结束了");};
return counter;
}
这个我好久才反应过来,原来这就是接口实现的一种方式。
总结了一下接口的实现方式的几种方式
1、可以使用<>的形式
interface IPerson {
firstName:string,
lastName:string,
sayHi: ()=>string
}
var customer=<IPerson> {
firstName:"Tom",
lastName:"Hanks",
sayHi: ():string =>{return "Hi there"}
}
2、可以使用implements的方式
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date;
constructor(h: number, m: number) { }
}
3、可以直接使用声明接口类型然后直接赋值
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ["Alice", "Bob"];//直接赋值
myArray[2] = "Mallory"; // error!```
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
这种方式似乎很像c语言等语言中的结构体类型。
最后
个人觉得ts语法有点乱,没办法,当我写到这里时有许多疑问的,想要尝试着各种写法试试有没有用。
但是能用就行,能看懂代码就够了。