接口: 只声明结构,不需要实现(有数据结构需要约束,这个时候就可以用接口)
interface Person {
firstName: string;
lastName: string;
}
function greeting(person: Person) {
console.log(person)
}
greeting({'firstName': '六', 'lastName': '十'})
类中的使用
interface Person {
firstName: string;
lastName: string;
}
class Hello {
private person: Person[];
constructor() {
this.person = [
{firstName: 'tom', lastName: 'timo'}
];
}
console.log(this.person)
}
new Hello();
泛型(理解为通用的类型)
interface Person {
firstName: string;
lastName: string;
}
interface Result {
ok: 0 | 1;
data: Person[];
}
data 中指定了类型为 Person 接口,当返回数据为其他接口类型时,就不通用,
这个时候需要指定为泛型,如下
interface Result<T> {
ok: 0 | 1;
data: T[];
}
指定占位符为 T,当将来使用时传入什么接口,那么返回就是什么接口