接口
最后更新于:2022-04-02 03:28:04
[TOC]
## 宽松版参数检查
非接口
```
function printLabel(labelledObj: { label: string }) {
console.log(labelledObj.label);
}
let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);
```
接口
```
interface LabelledObj{
label:string
}
function printLabel(labelledObj: LabelledObj) {
console.log(labelledObj.label);
}
let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);
```
## 可选属性
```
interface SquareConfig {
color?: string;
width?: number;
}
```
## 只读属性
`readonly`来指定只读属性:
```
interface Point {
readonly x: number;
readonly y: number;
}
```
```
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!
```
数组只读 `ReadonlyArray`
```
let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
a = ro; // error!
```
普通复制不被允许,只能通过断言赋值
`a = ro as number[];
`
## 定义函数类型
```
interface SearchFunc {
(source: string, subString: string): boolean;
}
```
参数名可不一致
```
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
}
```
有可在函数中取消类型声明
```
let mySearch: SearchFunc;
mySearch = function(src, sub) {
let result = src.search(sub);
return result > -1;
}
```
## 可索引的类型
如`a[10]`或`ageMap["daniel"]`
```
interface Foo{
[index:number]:string
}
let F:Foo
F=["a","b","c"]
F[0]==F['0'] //"a"
```
查询索引时,`number`与`string`相同
设置只读索引
```
interface ReadonlyStringArray {
readonly [index: number]: string;
}
let myArray: ReadonlyStringArray = ["Alice", "Bob"];
myArray[2] = "Mallory"; // error!
```
## 类接口
定义属性和方法
```
interface ClockInterface {
currentTime: Date;
setTime(d: Date);
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
getTime():string{
//可添加私有方法
return new Date().toLocaleTimeString()
}
constructor(h: number, m: number) { }
}
```
## 继承接口
```
interface Foo{
Name:string
}
interface Fooo extends Foo{
Age:number
}
let f = {Name:"cc",Age:12}
f.Name="ddd"
console.log(f.Name);
```
可继承多个接口
```
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
```
## 混合类型
```
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
function getCounter(): Counter {
let counter = function (start: number) { };
counter.interval = 123;
counter.reset = function () { };
return counter;
}
let c = getCounter();
c(10);
c.reset();
c.interval = 5.0;
```
';