ts中type和interface类型声明的区别

1. 写法上

type 使用关键字 type 进行声明。
interface 使用关键字 interface 进行声明。

// 使用 type
type MyType = {
   
  param: string;
};

// 使用 interface
interface MyInterface {
   
  param: string;
}

2. 可合并性

interface 具有可合并性,允许在同一作用域内多次声明同名的接口,这些声明将会合并为一个接口。
type 不具有可合并性,如果多次声明同名的类型,会报错。

// interface 具有可合并性
interface MyInterface {
   
  param: string;
}

interface MyInterface {
   
  additionParam: number;
}

// 最终合并后的接口
// { param: string; additionParam: number; }

3. 拓展性

interface支持接口的扩展(extends关键字)。
type 支持联合类型交叉类型,但不能使用 extends关键字 进行扩展。

// 使用 interface 扩展
interface ExtendedInterface extends MyInterface {
   
  newParam: string;
}

// 使用 type 交叉类型
type ExtendedType = MyType & {
    newParam: string};

ts类型操作符& 和 | 的区别

4. 接口的实现

class 可以用implements实现一个接口。
type 不能被类实现。

// 使用 interface 实现
interface MyInterface {
   
  prop: string;
}

class MyClass implements MyInterface {
   
  prop = "value";
}

5. 使用场景

一般来说,interface 更适合声明一个对象

interface Person {
   
  name: string;
  age: number;
  greet(): void;
}

const person: Person = {
   
  name: 'John',
  age: 30,
  greet() {
   
    console.log('Hello!');
  }
};

type更适合表示联合类型、交叉类型和其他高级类型,创建类型别名

type Status = 'success' | 'error';

type Coordinate = {
   
  x: number;
  y: number;
};

type Point3D = Coordinate & {
    z: number };

type FunctionType<T> = (arg: T) => void;

相关推荐

  1. tstypeinterface类型声明区别

    2023-12-11 00:46:03       42 阅读
  2. TypeScriptinterfacetype区别

    2023-12-11 00:46:03       27 阅读
  3. GPT每日面试题-Typescripttypeinterface区别

    2023-12-11 00:46:03       8 阅读
  4. TypeScriptinterfacetype差别是什么?

    2023-12-11 00:46:03       11 阅读
  5. [TS面试]TS类型全局声明与局部声明?

    2023-12-11 00:46:03       12 阅读
  6. Ts 接口interface 与 对象type 异同

    2023-12-11 00:46:03       47 阅读
  7. Pythontype() isinstance() 区别

    2023-12-11 00:46:03       20 阅读
  8. TSconstreadonly区别

    2023-12-11 00:46:03       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-11 00:46:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-11 00:46:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-11 00:46:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-11 00:46:03       18 阅读

热门阅读

  1. harmonyOS学习笔记之状态修饰器@state,@prop,@link

    2023-12-11 00:46:03       31 阅读
  2. 排列游戏 --- 动态规划 --- 题解

    2023-12-11 00:46:03       37 阅读
  3. Mysql多表查询 思路 ——示例——sql顺序

    2023-12-11 00:46:03       41 阅读
  4. 米贸搜|facebook广告的素材及文案

    2023-12-11 00:46:03       36 阅读
  5. 做题笔记:SQL Sever 方式做牛客SQL的题目--VQ

    2023-12-11 00:46:03       31 阅读
  6. 数据库基础--关系模型、范式、SQL、索引、事务

    2023-12-11 00:46:03       39 阅读