1.type与interface的区别:
区别一:interface只描述对象,type则描述所有数据:
type可以描述所有数据 :
type Name = string;
type FalseLike = '' | 0 | false | null | undefined;
type Point = {x:number; y:number};
type Points = Point[];
type Line = [Point,Point];
type Circle = {center:Point,radius:number};
type Fn = (a:number,b:number) => number;
type FnWithProps = { // 带有属性的函数,使用时需调用函数属性,如f.prop1 = 1
(a:number,b:number):number
prop1:number
}
interface只描述对象:
interface A = { [k:string]:number }
interface Point { x:number,y:number }
interface Points extends Array<Point> {}
interface Fn {(x:number,y:number):number;}
interface FnWithProps {
(x:number,y:number):number
prop1:number
}
const f: Fn = (x,y) => { return x+y }
f.prop1 = 1
interface Date2 extends Date {}
interface A1 extends Array<string>{} // 等价于 type A1 = Array<string>
interface A2 extends Array<string>{ name:string }
// 等价于 type A1 = Array<string> & { name:string }
interface X = { age:number }
interface A2 extends Array<string>,X { name:string }
// 等价于 type A1 = Array<string> & { name:string } & X
区别二:type只是别名,interface则是类型声明(声明接口,描述对象的属性)
type是类型别名(Type Aliases),相当于只是给其它类型取个名字:
type A = string, type B = A,此时 B = string,A只是string的别名
而interface则是类型声明:
interface D extends Date {},type E = D,此时的 E = D,D是一个类型
区别三:type不可重新赋值,而interface可以自动合并(可扩展)
type A = number,声明后 A 不能再重新赋值(不可扩展)
注:type可通过继承的方式扩展:
type A = { name:string }
type B = { age:number } & A
const s: B = {
name:'lgt',
age:22
}
interface多次声明可以自动合并(可扩展)
interface X { name:string }
interface X { age:nummber }
const a:X {
name:'xrr',
age:24
}
interface可以用来扩展axios或者扩展String等.
总结:对外API尽量用interface,方便扩展;对内API尽量用type,防止代码分散。