- interface 接口:描述对象的形状和结构,可以给数据增添类型,而且方便复用
- type 别名:通过别名来重新定义类型
1. 描述对象类型
interface IObj { // 名称前一般加个大写 I
name: string // 结尾不写或加 , ; 都可以
age: number
}
// type IObj = {name: string, age: number} | string; // 如果有联合类型,就使用 type
const getObj = (obj: IObj) => {} // 接口使用联合类型,在()中 | string
getObj({name: 'Tom', age: 18});
2. 描述函数类型
interface ISum {
(a: string, b: string): string
}
//type ISum = (a: string, b: string) => string // 描述函数使用type更方便
const sum: ISum = (a, b) => {
return a + b;
}
3. 函数混合类型
interface ICount { // 接口中的混合类型
(): number
count: number
}
const fn: ICount = (() => { // 函数返回函数,一般要标识函数的返回类型
return ++fn.count;
}) as ICount
fn.count = 0;
4. 接口的特性
interface IVegetables {
color:string;
taste:string
}
- 直接断言 (前提:接口中限制的2个数据必须要有)
const tomato:IVegetables = {
color:'red',
taste:'sweet',
size:'big' // 多的数据使用断言
} as IVegetables // 断言
- 接口的合并
// 接口同名会合并,会改变原有的接口
interface IVegetables {
size:string
}
const tomato:IVegetables = {
color:'red',
taste:'sweet',
size:'big'
}
- 接口的继承
interface ITomato extends IVegetables{
size:string
}
const tomato:ITomato = {
color:'red',
taste:'sweet',
size:'big'
}
- 可选属性
interface IVegetables {
color: string,
taste: string,
[key: string]: any // 任意接口 可多填
// size?:string // 可以通过 ? 来实现
// id?:number
}
const tomato: IVegetables = {
color: 'red',
taste: 'sweet',
size: 'big',
id: 123
}
- 可索引接口
interface ILikeArray {
[key: number]: any
}
let arr: ILikeArray = [1, 2, 3];
let arr1: ILikeArray = { 1: 1, 2: 2 };
- 接口中的类型
// 接口中的类型 可以通过类型别名的方式拿出来 , 但是只能用[]语法
// 嵌套的情况
type MyType = {key:string,value:string}
interface XXX {
n:MyType[]
}
interface IArr {
arr:MyType[],
a:XXX
}
type My = IArr['a']['n']
- 接口实现
接口可以被类来实现 , 接口中的方法都是抽象(没有具体实现)的
interface ISpeakable {
name: string,
// 用接口来形容类的时候 void 表示不关心返回值
speak(): void // 描述当前实例上的方法,或者原型的方法
}
interface IChineseSpeakable {
speakChinese(): void
}
class Speak implements ISpeakable, IChineseSpeakable { // 类本身需要实现接口中的方法
speakChinese(): void {
throw new Error("Method not implemented.");
}
name!: string
speak(): string { // 此方法是原型方法
return 'xxx'
}
}
let s = new Speak()
5. 抽象类(不能被new,可以被继承)
abstract class Animal { // 只有类被标记成abstract 属性在可以描述成abstract的
abstract name: string // 没有具体实现,需要子类实现
eat() {
console.log('eat')
}
abstract drink(): void // 没有具体实现,子类必须实现
}
class Cat extends Animal {
drink(): void {
console.log('Method not implemented')
}
name: string = 'a'
}
// abstract(可以放置具体的实现) interface (只能放一些抽象的属性和方法 不能有具体实现)
6. 描述实例
// 单例模式
// let instance: Person;
// type IPerson = new (name:string)=>Person 描述的是构造函数类型
interface IPerson<T> {
new(name: string): T
}
function createInstance<T>(clazz: IPerson<T>, name: string) {
// if (instance) return instance;
return new clazz(name)
}
class Person {
eat() { }
constructor(public name: string) { }
}
class Dog {
drink() { }
constructor(public name: string) { }
}
// 泛型就是只有当使用的时候 才能确定类型, 通过参数传入类型
let r = createInstance<Person>(Person, '张三'); // 类可以充当类型,可以描述实例
r.eat()