TypeScript – interface
- 概念: TypeScript接口定义对象的类型(我的理解:定义对象属性的类型和提炼类中的公共方法)
- 类别:
- 接口的可选属性: 接口中的属性不全是必须的, 带有可选属性的接口和普通的接口差不多, 只是在可选属性后添加 ’ ?’
// 可选属性的接口
interface SquareConfig {
color? : string;
width? : number;
}
function createSquare(config: SquareConfig): {"color": string, "area": number} {
let newSquare = {color: "white", area: 100};
if (config.color) {
newSquare.color = config.color;
}
if (config.width) {
newSquare.area = config.width * config.width;
}
return newSquare;
}
let mySquare = createSquare({color: "black"});
console.log(mySquare);
- 只读属性: 接口中的一些属性只能在对象刚刚创建时修改其值, 在只读属性前 添加 ’ readonly’
- TypeScript具有ReadonlyArray类型,它与Array相似,只是把所有可变方法去掉了,因此可以确保数组创建后再也不能被修改:
// 只读属性的接口
interface Point {
readonly x : number;
readonly y : number;
}
export class AppComponent implements OnInit {
// 只读属性的接口
readonlyFun(): void {
console.log("这是只读属性的接口");
let p1: Point = {x: 10, y: 10};
console.log(p1);
// error
// p1.x = 5;
// ReadonlyArray<number>
let a: number[] = [1,2,3,4];
let ro: ReadonlyArray<number> = a;
console.log(ro);
// ro[0] = 12;
}
const: 用于目标标识符是变量
readonly: 用于目标标识符是对象属性
- 函数类型接口: 给接口定义一个调用签名。 它就像是一个只有参数列表和返回值类型的函数定义。参数列表里的每个参数都需要名字和类型
- 函数的参数名不需要与接口里定义的名字相匹配
// 函数类型
interface SearchFunc {
(source: string, subString: string): boolean;
}
export class AppComponent implements OnInit {
// 函数类型 sou: string, sub: string
mySearch: SearchFunc = function (source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
ngOnInit() {
console.log(this.mySearch('nihao1234566', 'nihao'));
}
}
- 索引类型的接口: 可索引类型具有一个索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。
// 索引类型
interface StringArry {
[index: number]: string;
}
export class AppComponent implements OnInit {
// 索引类型
stringArray(): void {
let myArry: StringArry;
myArry = ["Bod", "Fred"];
let myStr: string = myArry[0];
console.log(myStr);
}
ngOnInit() {
this.stringArray();
}
}
- 接口继承: 接口之间可以相互继承
- 混合类型: 接口属性可以是多种类型
- 接口继承类: 接口继承类中的成员(包括私有和公有),实现接口只能由其子类实现