typeScript interface和type区别
interface 参考资料 ----> https://www.tslang.cn/docs/handbook/interfaces.html
// ts 自定义类型
/**
* Interface(接口) vs Type alias(类型别名)
* 相同点-> 都可以描述一个对象或者函数
* -> 都允许拓展(extends)
* --->> interface extends interface (接口继承接口)
* --->> type extends type (类型继承类型)
* --->> interface extends type (接口继承类型)
* --->> // type extends interface (类型继承接口)
*/
// interface
interface UserOP { // 描述一个对象
name: string;
email: string;
isBig: boolean;
age: number;
}
interface SetUser { // 描述一个函数
(name: string, email: string, isBig: boolean, age: number): UserOP;
}
let pikaqiu: UserOP; // 创建一个变量是 UserOP的类型
pikaqiu = { name: 'zyn', email: 're', isBig: false, age: 34 }
let mySearchXX: SetUser; // 用来描述一个方法
mySearchXX = function (name: string, email: string, isBig: boolean, age: number): UserOP {
return pikaqiu;
}
// type
type UserTy = {
name: string
age: number
};
type SetUserTy = (name: string, age: number) => void;
let pikaqiu1: UserTy;
pikaqiu1 = { name: 'zyn', age: 54 };
let mySearchXXTy: SetUserTy;
mySearchXXTy = function (name: string, age: number) {
}
// interface extends interface (接口继承接口)
// 1. interface 属性继承
interface dudu1 {
name: string
}
interface dudu2 extends dudu1 {
age: number
}
const duduTest: dudu2 = { name: 'zyb', age: 23 };
// type extends type (类型继承类型)
type Nametype = {
name: string;
}
type UserType = Nametype & { age: number };
const valueType: UserType = { name: 'zyb', age: 23 };
// interface extends type (接口继承类型)
type LulvwaType = {
name: string
}
interface LulvwaFace extends LulvwaType {
age: number;
}
const LulvwaValue: LulvwaFace = { name: 'zyb', age: 23 };
// type extends interface (类型继承接口)
interface shajFace {
name: string
}
type shajType = shajFace & {
age: number;
}
const shajValue: shajType = { name: 'zyb', age: 23 };
/**
* Interface(接口) vs Type alias(类型别名)
* 不同点-> type 可以而 interface 不行
* -----> type 可以声明基本类型别名,联合类型,元组等类型
* -> interface 可以而 type 不行
* -----> interface 能够声明合并
*/
// 基本类型别名
type DiffName = string;
// 联合类型
interface Dog {
wong();
}
interface Cat {
miao();
}
type Pet = Dog | Cat
// 元祖类型
type PetList = [Dog, Pet]
// interface 能够声明合并
interface DiffLx {
name: string
}
interface DiffLx {
age: number
}
interface DiffLx {
sex: string
}
// 合并后的结果
/*
interface DiffLx {
name: string
age: number
sex: string
}
*/
const DiffLxValue: DiffLx = { name: '34', age: 34, sex: 'nv' }