interface
interface loginForm {
username:string,
password?:string, //可选属性
readonly y: number; //只读属性
}
const form:loginForm = reactive({
username: "",
password: '',
})
//接口函数
interface SearchFunc{
(source:string,subString:string):boolean
}
let mySearch:SearchFunc
mySearch = (a:string,subString:string)=>{ //函数的参数名不需要与接口里定义的名字相匹配
let result = a.search(subString);
return result >-1
}
mySearch("22","#33")
//接口数组
```javascript
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];
//继承接口
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
数组只读
```javascript
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a; //只读
a = ro as number[]; //使用类型断言重写,可以修改
泛型
function identity<T>(arg:T):T{
return arg
}
console.log(identity<string>("123")) //调用函数 ,string传入类型
//注意我们没必要使用尖括号(<>)来明确地传入类型;编译器可以查看myString的值,然后把T设置为它的类型。
//类型推论帮助我们保持代码精简和高可读性。如果编译器不能够自动地推断出类型的话,只能像上面那样明确的传入T的类型
//在一些复杂的情况下,这是可能出现的
数组类型
function loggingIdentity<T>(arg: T[]): T[] {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
//也可以这样写
function loggingIdentity<T>(arg: Array<T>): Array<T> {
console.log(arg.length); // Array has a .length, so no more error
return arg;
}
loggingIdentity([1,2,3])
//调用函数
function identity<T>(arg:T):T{
return arg
}
let Myidentity:<T>(arg:T)=>T = identity
let Myidentity1:{<T>(arg:T):T} = identity