跳到主要内容

TS中的接口interface 和 type语句有什么区别?

参考答案:

在TypeScript(TS)中,interfacetype语句都可以用来定义类型,但它们之间有一些关键的区别。

  1. 语法

    • Interface:使用interface关键字来定义。
    	typescript`interface Person {
    	    name: string;
    	    age: number;
    	}`
    
    • Type Alias:使用type关键字来定义。
    	typescript`type Person = {
    	    name: string;
    	    age: number;
    	};`
    
  2. 扩展性

    • Interface:可以被其他接口扩展(继承)。
    	typescript`interface Animal {
    	    live(): void;
    	}
    
    	interface Mammal extends Animal {
    	    breastFeed(): void;
    	}`
    
    • Type Alias:不能直接扩展,但可以使用交叉类型来实现类似的功能。
    	typescript`type Mammal = Animal & {
    	    breastFeed(): void;
    	};`
    
  3. 函数类型

    • Interface:在接口中,方法默认是public的,且不能定义为静态方法。
    • Type Alias:在类型别名中,可以定义函数类型,包括静态方法。
    	typescript`type Add = (a: number, b: number) => number;
    
    	type Calculator = {
    	    add: Add;
    	    staticSubtract: (a: number, b: number) => number;
    	};`
    
  4. 字符串字面量类型

    • Type Alias:可以直接定义字符串字面量类型。
    	typescript`type Easing = "ease-in" | "ease-out" | "ease-in-out";`
    
    • Interface:不能直接定义,但可以通过字符串索引签名来模拟。
  5. 兼容性

    • Type Alias:对于TypeScript来说,它是一个真正的类型,这意味着类型别名之间的赋值关系是完全的类型安全检查。
    • Interface:在某些情况下,可能表现得像是一个类型,但在其他情况下,它可能表现得像是一个对象。
  6. 声明合并

    • 在TypeScript中,对于同一个接口,可以多次声明并自动合并。但对于类型别名,不能这样做。
  7. 默认值

    • 在类型别名中,可以为属性设置默认值。
    	typescript`type Person = {
    	    name?: string;
    	    age?: number;
    	};`
    
    • 接口不支持这种特性。

总之,interfacetype在TypeScript中都有各自的用途和优势。选择使用哪一个通常取决于你的具体需求和偏好。