首页 前端知识 typescript中type、interface的区别

typescript中type、interface的区别

2025-03-05 17:03:08 前端知识 前端哥 838 217 我要收藏

一、概念定义

  1.  interface:接口
    • 在TS 中主要用于定义【对象类型】,可以对【对象】的形状进行描述。
  2. type :类型别名
    1. 为类型创建一个新名称,它并不是一个类型,只是一个别名。

二,区别

  1. interface:
    1. interface用来定义一个类结构,可以声明多个
      interface myInterface{
      	name: string;
      	age: number;
      }
      interface myInterface{
      	gender: string;
      }
      
      const obj: myInterface = { 
      	name: 'zhangsan',
      	age: 111,
      	gender:'男'
      };
    2. 使用interface声明,可以被继承扩展使用
      interface Inter{
      	length: number;
      }
      function fn3<T extends Inter>(a: T): number{ 
      	return a.length;
      }
      
      fn3( a: 10);
  2. type:
    1. type可以定义
      1. 基本类型别名,如type StringType = string
      2. 联合类型,如 type paramType = number | string;
      3. 可以声明元组类型,如type arrType = [string, string, number]
    2. type声明可以交叉扩展
      type Animal {
      	name: string
      }
      type Bear & Animal {
      	honey: boolean
      }
      

转载请注明出处或者链接地址:https://www.qianduange.cn//article/22727.html
标签
评论
发布的文章

python连接neo4j的方式汇总

2025-03-05 18:03:12

五子棋对弈

2025-03-05 18:03:12

奖学金(acwing)c

2025-03-05 18:03:11

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!