//接口
interface labelValue {
label: string;
}
//函数在此处定义了函数接口,传入的值会被接口进行检查
function test(labelObject: labelValue) { //接口定义了,传入的值必须有label属性
console.log(labelObject.label) //并且属性是string
}
let myobj = { size: 10, label: "sssssssss" };
test(myobj)
//可选属性对可能存在的属性进行预定义
interface sconfig {
color?: string;
width?: number;
}
function square(config: sconfig): { color: string; area: number } {
let newS = { color: "white", area: 100 }
if (config.color) {
newS.color = config.color
}
if (config.width) {
newS.area = config.width;
}
return newS;
}
let mysquare = square({ color: "black" })
console.log(mysquare) //{ color: 'black', area: 100 }
//只读属性
interface Point {
readonly x: number;
readonly y: number;
}
let p1: Point = { x: 10, y: 20 }; //给变量指定接口,只读属性的变量无法修改
let a: number[] = [1, 2, 3, 4, 5, 6];
let ro: ReadonlyArray = a; //设置为只读数组
// ro[0] = 12; //报错
//字符串索引签名
//接口表明,除了color和width得是定义了的可选属性
//其他的属性都可以
interface SquareConfig {
color?: string;
width?: number;
[propName: string]: any
}
//接口描述函数
interface SearchFunc { //函数参数是string和string,返回值是boolean
(source: string, substring: string): boolean
}
let mySearch: SearchFunc; //函数定义接口
mySearch = function (source: string, substring: string) {
let result = source.search(substring)
return result > -1 //返回值是boolean
}
//函数类型的类型检查,函数的参数名不需要与接口里面的名字相匹配
//接口的可索引的类型
interface StringArray {
[index: number]: string; //string数组类型 number索引类型
}
let myArray: StringArray; //定义了myArray的接口
myArray = ["bob", "fred"]; //赋值
let mystr: string = myArray[0]; //索引取值
console.log(mystr) //bob
注意索引签名的问题
//索引签名的问题
interface NumberDictionary {
[index: string]: number; //此处索引是number
lenght: number;
//name: string; //error name的类型是string,索引是number
}
//定义只读索引接口
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let arr: ReadonlyStringArray = ["aa", "bb"];
interface shape {
color: string;
}
//接口Square继承了shape接口的成员
interface Square extends shape {
sideLength: number;
}
let sq = {};
sq.color = "blue";
sq.sideLength = 10;
//接口的多重继承 SSS继承了shape和pen的接口成员
interface SSS extends shape, pen {
sideLength: number
}
let qqq = {};
square.color = "blue";
square.penWidth = 10;
一个对象同时可以作为对象和函数使用
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getContent(): Counter {
let counter = function (start: number) { }; //???
counter.interval = 123;
counter.reset = function () { };
return counter
}
let cc = getContent();
cc(10);
cc.reset();
cc.interval = 5.0;