TS中type和interface的区别

TypeScript的Type和Interface是两种类型定义方式,Type用于创建类型别名,可以定义基本类型、联合类型和元组,而Interface主要描述对象类型,支持接口继承。Type不能重复声明,Interface可以。此外,Type能表示非对象类型,Interface则不能。
部署运行你感兴趣的模型镜像

概念:

type:类型别名,为类型创建一个新名称。它并不是一个类型,只是一个别名。

interface:接口,TS 设计出来主要用于定义对象类型,可以对对象的形状进行描述。

区别:

1.interface可以重复声明,type定义后不能重复声明

 

 2.interface可以通过“extends”来继承接口,这样既高效又不用重新定义。而type只能通过&来实现类似于继承的功能

3.

type 能够表示非对象类型, 而 interface 则只能表示对象类型

type

  • 可以定义基本类型别名,如type StringType = string
  • 可以声明联合类型,如 type paramType = number | string;
  • 可以声明元组类型,如type arrType = [string, string, number]

定义对象时严谨的来说,type 是引用,而 interface是定义。

 

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

TypeScript 中,`type` `interface` 都用于定义类型,但它们在功能使用场景上有显著差异。理解这些差异有助于在合适的上下文中选择更合适的抽象方式。 ### 1. 定义与用途 `interface` 主要用于定义对象的结构,包括属性、方法、索引签名等,适用于描述对象类型的形状。它支持继承、声明合并等特性,适用于面向对象的设计模式。 ```typescript interface Person { name: string; age: number; } ``` `type` 是类型别名,可以为任何类型(包括原始类型、联合类型、元组、函数类型等)创建新的名称,适用于更通用的类型定义。 ```typescript type ID = number | string; type Point = { x: number; y: number }; ``` ### 2. 扩展性 `interface` 支持通过 `extends` 关键字进行继承,且可以多继承,即一个接口可以继承多个其他接口。 ```typescript interface Animal { name: string; } interface Bear extends Animal { honey: boolean; } ``` `type` 不能直接“继承”,但可以通过交叉类型 `&` 实现类似效果。 ```typescript type Animal = { name: string }; type Bear = Animal & { honey: boolean }; ``` ### 3. 声明合并 `interface` 支持**声明合并**(Declaration Merging),即多个同名接口会自动合并为一个接口,适用于扩展已有接口。 ```typescript interface Box { width: number; } interface Box { height: number; } // 实际上合并为 { width: number; height: number } ``` `type` 不支持声明合并,重复定义同名 `type` 会导致编译错误。 ### 4. 重新声明 由于 `interface` 支持声明合并,因此可以多次定义同名接口,而 `type` 不允许重复定义同名类型别名。 ### 5. 类实现(implements) `interface` 可以被类显式实现(`implements`),而 `type` 虽然也可以被类实现,但前提是该类型别名表示的是一个对象结构。 ```typescript interface Logger { log(message: string): void; } class ConsoleLogger implements Logger { log(message: string) { console.log(message); } } ``` ### 6. 映射类型(Mapped Types) `interface` 不能直接参与映射类型操作(如 `Pick`、`Record` 等),而 `type` 可以直接用于这些操作。 ```typescript type User = { id: number; name: string; email: string; }; type PartialUser = Partial<User>; type UserNameOnly = Pick<User, 'name'>; ``` ### 7. 联合类型与基本类型别名 `type` 可以定义联合类型、基本类型别名、元组等复杂类型,而 `interface` 仅能描述对象类型。 ```typescript type Status = 'active' | 'inactive'; type Coordinates = [number, number]; ``` ### 8. 类型推导与兼容性 `interface` 在类型兼容性方面更加严格,尤其在类实现函数参数的类型检查中。`type` 更加灵活,适合用于类型组合类型操作。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值