欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > type和interface的继承

type和interface的继承

2024/10/24 8:25:00 来源:https://blog.csdn.net/kuang_nu/article/details/139546610  浏览:    关键词:type和interface的继承

type的复用:

type Point = {x: number;y: number;
};type Coordinate = Point & {z: number;
};

解释:

这段代码是TypeScript中的类型定义,使用了TypeScript的类型别名(type)和交叉类型(&)的特性。

  • 定义Point类型:

       type Point = {

         x: number;

         y: number;

       };

    这里定义了一个名为Point的类型,它是一个对象类型,包含两个属性:x和y,这两个属性的类型都是number。
  • 定义Coordinate类型:

       type Coordinate = Point & {

         z: number;

       };

    Coordinate类型是通过交叉类型创建的,它结合了Point类型和一个额外的属性z。交叉类型Point & { z: number }意味着Coordinate类型的对象将包含Point类型的所有属性(即x和y),并额外包含一个名为z的属性,其类型为number。

因此,一个Coordinate类型的对象将有三个数值属性:x、y和z。这种方式常用于扩展已有的类型或组合多个类型的属性到一个新的类型中.

用原始方法写不使用复用的语法:

type Coordinate = {

  x: number;

  y: number;

  z: number;

};

interface的复用:

interface Point {x: number;y: number;
};interface Coordinate extends Point {z: number;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com