定义接口
interface Point {
x: number;
y: string;
}
let p1: Point = { x: 10, y: "abc" };
p1.y = 5; // error!
函数内使用
interface NameInfo {
firstName: string;
lastName: string;
}
const getFullName = ({ firstName, lastName }: NameInfo): string => {
return `${firstName} ${lastName}`;
};
getFullName({
firstName: "name1",
lastName: "name2"
});
可选参数"?"
interface Vegetable {
color?: string;
type: string;
}
readonly: 只读属性
interface ArrInter {
0: number;
readonly 1: string;
}
const arrInter: ArrInter = [0, "a"];
// arrInter[1] = "b"; // err
索引签名
索引签名类型只能为 number / string
interface RoleDic {
[id: number]: string;
}
const role1: RoleDic = {
0: "第一个属性key为number,val为string"
};
interface RoleDic1 {
[id: string]: string;
}
const role2: RoleDic1 = {
2: "索引签名为number时,不会报错,因为js会将对象属性名转换为string"
};
接口的继承
interface Vegetables {
color: string;
}
interface Tomato extends Vegetables {
length: number;
}
const tomato: Tomato = {
color: "red",
length: 2
};
函数添加属性
interface Counter {
(): void;
count: number;
}
const getCounter = (): Counter => {
const c = () => {
c.count++;
};
c.count = 0;
return c;
};
const counter: Counter = getCounter();
counter();
console.log(counter.count);
在js中的实现:
const fn1 = () => {
fn1.num++;
};
fn1.num = 0;
fn1();
console.log(fn1.num);