关于typescript:TypeScript中interface和type

TS中interface(接口)和type(类型别名)有许多相似之处:

  • 理论开发中两者都能够用来束缚变量的类型
  • 两者都能够扩大
  • 接口和类型别名不是互斥的,接口能够扩大类型别名,反之亦然

上面次要来看下区别

1、申明形式不同
interface Point {
  x: number;
  y: number;
}

interface SetPoint {
  (x: number, y: number): void;
}
type Point = {
  x: number;
  y: number;
};

type SetPoint = (x: number, y: number) => void;
2、类型别名(type)还能够用于其余类型,如根本类型(原始值)、联结类型、元组
// primitive
type Name = string;

// union
type PartialPoint = PartialPointX | PartialPointY;

// tuple
type Data = [number, string];

// dom
let div = document.createElement('div');
type B = typeof div;
3、扩大时语法不同,且interface无奈扩大联结类型的type
interface PartialPointX { x: number; }
interface Point extends PartialPointX { y: number; } 
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; }; 
type PartialPoint = { x: number; } | { y: number; };

// 报错:无奈实现一个联结类型的type
// class SomePartialPoint implements PartialPoint {
//   x: 1;
//   y: 2;
// }
4、interface能够定义屡次,并将被视为单个接口(合并所有申明的成员);type不能够
interface Point { x: number; }
interface Point { y: number; }

const point: Point = { x: 1, y: 2 };
5、interfac能够extends class,class也能够implements interface
class Point {
    x: number;
    y: number;
}

interface Point3d extends Point {
    z: number;
}
interface Foo {
    name: string;
    age: number;
    sayHello(): void;
}

class Bar implements Foo {
    name: string;
    age: number;
    sayHello(): void {
        console.log('Hello');
    }
}
6、type反对计算属性,生成映射类型,interface不能够
  • type 能应用 in 关键字生成映射类型,但 interface 不行
  • 语法与索引签名的语法类型,外部应用了 for .. in
type Keys = "firstname" | "surname"

type DudeType = {
  [key in Keys]: string
}

const test: DudeType = {
  firstname: "Pawel",
  surname: "Grzybek"
}

// 报错
//interface DudeType2 {
//  [key in keys]: string
//}

总结:我平时开发中,习惯在一个module下新建一个公共文件interface.ts,专门export各种interface,用于束缚以后module业务代码中各种变量的类型和取值范畴;如果独自某个组件中的变量取值范畴比拟非凡,那就在其组件业务代码中用type束缚下

【腾讯云】轻量 2核2G4M,首年65元

阿里云限时活动-云数据库 RDS MySQL  1核2G配置 1.88/月 速抢

本文由乐趣区整理发布,转载请注明出处,谢谢。

您可能还喜欢...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据