(附TS中文网相关学习链接:TypeScript 中文手册 - 接口(interface))
TS 中的接口与 Java 中的接口完全不一样。TS 中的接口更像是给对象的一个约定。
“需要注意的是,我们在这里并不能像在其它语言里一样,说某个对象实现了这个接口。”——TypeScript 中文手册
接口能够描述JavaScript中拥有的各种各样的外形对象,包括函数、类数组、普通对象等。
(PS:建议学过Java的人慎重接触这部分,因为会完全颠覆你对 interface、class 的理解)
interface SomeInterface {
somAttr?: attrValue;
}
好处:
interface SomeInterface {
readonly somAttr: attrValue;
}
只读数组:
ReadonlyArray
将某个对象字面量赋值给变量或作为参数传递的时候,对象字面量会经过额外属性检查—— 如果一个对象字面量存在任何“目标类型”不包含的属性时,将会得到一个错误:error: 'someAttr' not expected in type 'SomeInterface'
interface 的字符串索引签名
interface SomeInterface {
somAttr: attrValue;
[propName: string]: any;
}
接口定义:
interface MyFunction{
(source: string, subString: string): boolean;
}
上述的 boolean 即函数返回值类型。
使用接口定义函数:
let MyFunction: MyFunction;
MyFunction= function(source: string, substr: string) {
// 函数的实现
return true;
// or: return false;
}
比如:使用数字作为索引,且索引的结果为字符串
interface StringArray {
[index: number]: string;
}
(注:JS和TS中的一个数组内都可以保存不同类型的元素,可索引类型可以用来限制数组的元素类型。当然也可以用Array
设置索引类型为只读:
interface ReadonlyStringArray {
readonly [index: number]: string;
}
类静态部分与实例部分的区别
官网给了一段代码,表示理解不了:
interface ClockConstructor {
new (hour: number, minute: number): ClockInterface; //(不明白为啥这里要用 new 关键字)
}interface ClockInterface {
tick(): void;
}function createClock(ctor: ClockConstructor, hour: number, minute: number): ClockInterface {
return new ctor(hour, minute);
}class DigitalClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() {
console.log("beep beep");
}
}class AnalogClock implements ClockInterface {
constructor(h: number, m: number) {}
tick() {
console.log("tick tock");
}
}let digital = createClock(DigitalClock, 12, 17);
let analog = createClock(AnalogClock, 7, 32);
实现接口、继承接口
这部分的用法和Java中类与接口的基本用法相同。接口中声明方法和变量,在类中实现这些方法。
混合类型
这个感觉有点离谱:一个 Object 既可以当做 function 使用,也可以当做普通的 object 使用。比如:有一个对象 likeFunc
个人觉得一个对象还是纯粹一点好,除非非常非常特殊的情况。
(学过 JAVA 的我内心已经崩溃)
“当接口继承了一个类类型时,它会继承类的成员但不包括其实现。”此时接口会继承类的所有成员,包括私有成员和保护成员。这样造成的结果是:这个接口类型只能被这个类或其子类所实现。
class Control {
private state: any;
}interface SelectableControl extends Control {
select(): void;
}class Button extends Control implements SelectableControl {
select() { }
}class TextBox extends Control {
}
// Error: Property 'state' is missing in type 'Image'.
class Image implements SelectableControl {
select() { }
}class Location {
}
SelectableControl 接口继承自 Control 类,Button 类继承自 Control 类且实现了 SelectableControl 接口,TextBox继承自 Control 类,而Image 类仅仅实现了SelectableControl 接口。Location 类既没有继承 Control 也没有实现 SelectableControl。
这样导致的结果就是:TextBox 、Button 两个类具有 state 属性,而仅仅实现了 SelectableControl 接口的 Image 类没有 state 属性。
嗯………………………………是不是有点晕?自己画个类图理解一下吧。
(个人觉得这样的做法很不纯粹,用得好就是大神操作,用得不好就是灾难后果,新手表示不敢用)
总体来说需要明确一点:不要把其他面向对象语言的相关概念带进来,否则最后会学到你想shi
因为真的会污染你前面学到的知识!!!
因为真的会污染你前面学到的知识!!!
因为真的会污染你前面学到的知识!!!
所以请慎重!