一、type的使用方法
// 通过类型(type)来声明对象类型
type UserInfoType = {
name: string;
age: 18;
};
const userInfo: UserInfoType = {
name: 'Xilanhua',
age: 18,
};
二、interface的使用方法
/**
* 另外一种方式声明对象类型,使用 interface
* interface 用来定义一个类结构,用来定义一个类中应该包含哪些属性和方法
* 同时 interface 也可以当成类型声明去使用,可以定义可选属性,也可以定义只读属性
*/
interface UserInfoType2 {
readonly name: string;
age?: number;
};
const userInfo2: UserInfoType2 = {
name: 'John'
};
三、interface和type的区别
区别一: type类型使用范围更广,接口类型只能用来声明对象
// type 可以声明基础类型、联合类型、元组、枚举、类、接口、函数、对象等
type NameType = number | string;
type userType = {
name: string;
age: number;
};
// interface 可以声明接口、函数、对象等
interface infoInterface {}
区别二: 在声明对象时,interface可以多次声明
/**
* type 只能声明一次, 不能重复声明,会报错
* 不允许两个相同名称的别名同时存在
*/
type userType = {
name: string;
age: number;
};
// err, 重复声明
// type userType = {
// address: string;
// }
const obj: userType = {
name: 'lison',
age: 18
};
/**
* interface 可以声明多次, 会进行合并
* 允许两个相同名称的接口同时存在
* 使用时,合并的属性会叠加,方法会进行合并,同名方法会被覆盖 => 必须都使用上
*/
interface userInterface {
name: string;
}
interface userInterface {
age: number;
address?: string;
}
const info: infoInterface = {
// name和age都必须使用,否则报错, address可选
name: 'lison',
age: 18
};
区别三: interface可以实现继承
// interface可以实现继承
interface IPerson {
name: string;
age: number;
}
interface IXilanhua extends IPerson {
secret: string;
}
const smallBlack: IXilanhua = {
// name 和 age 和 secret 都是必须的
name: '西兰花',
age: 18,
secret: '西兰花是一条鱼'
};
区别四: interface可以被类实现
// interface可以被类实现
interface IPerson {
name: string;
age: number;
}
class Person implements IPerson {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
四、总结
如果是非对象类型的定义 => 使用type
如果是对象类型的声明 => 使用interface,会更加灵活