TS中的接口(interface)与类型别名(type alias)

TS中的接口(interface)与类型别名(type alias)

定义

在 typescript 中, 我们声明类型有两种方式: 接口(interface) 和类型别名(type alias),官方文档对于两者及其异同的描述如下:

One of TypeScript’s core principles is that type checking focuses on the shape that values have. This is sometimes called “duck typing” or “structural subtyping”. In TypeScript, interfaces fill the role of naming these types, and are a powerful way of defining contracts within your code as well as contracts with code outside of your project.

TypeScript 的核心原则之一是类型检查重点在于值的形状(values’ shape)。这种类型常被称为“鸭子类型(duck typing)”或“结构化子类型(structural subtyping)”。在 TypeScript 中,接口(interfaces)就是充当命名这些类型的角色,并且是在代码内或代码外定义约定(contracts)的有效方式。

PS: 在程序设计中,“鸭子类型”是动态类型的一种风格。在这种风格中,一个对象有效的语义,不是由继承自特定的类或实现特定的接口,而是由“当前方法和属性的集合”决定

Type aliases create a new name for a type. Type aliases are sometimes similar to interfaces, but can name primitives, unions, tuples, and any other types that you’d otherwise have to write by hand.

类型别名(type aliases)为一个类型创建一个新的名字。有些时候类型别名与接口(interfaces)很相似,但是类型别名可以用于声明原始类型(primitives),联合类型(unions),元组类型(tuples),还有其它一些你必须要手写的类型。

区别

1. 声明对象和函数类型的语法不一样

interface

interface A {
   
  x: number;
  y: string;
}
interface B {
   
  (x: number, y: string)
  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值