typescript和js的区别

人气:349 ℃/2023-03-06 03:34:51

TypeScript和JavaScript都是非常火爆的栈技术编程语言,那这两者有什么区别吗?一起来了解一下。

TypeScript和JavaScript是目前项目开发中较为流行的两种脚本语言,typescript和js的区别:

1、TypeScript 可以使用 JavaScript 中的所有代码和编码概念,

2、TypeScript 从核心语言方面和类概念的模塑方面对 JavaScript 对象模型进行扩展。

3、JavaScript 代码可以在无需任何修改的情况下与 TypeScript 一同工作,同时可以使用编译器将 TypeScript 代码转换为 JavaScript。

4、TypeScript 中的数据要求带有明确的类型,JavaScript不要求。

5、TypeScript 引入了 JavaScript 中没有的“类”概念。

6、TypeScript 中引入了模块的概念,可以把声明、数据、函数和类封装在模块中。

TypeScript是一种由微软开发的自由和开源的编程语言。它是JavaScript的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程。

typescript interface和type的区别

TypeScript 中 type 和 interface 有什么区别?

大家好,我是前端西瓜哥,今天我们来看看 type 和 interface 的区别。

type 和 interface

type 是 类型别名,给一些类型的组合起别名,这样能够更方便地在各个地方使用。

假设我们的业务中,id 可以为字符串或数字,那么我们可以定义这么一个名为 ID 的 type:

typeID=string|number;

定义一个名为 Circle 的对象结构 type:

typeCircle={x:number;y:number;radius:number;}

interface 是 接口。有点像 type,可以用来代表一种类型组合,但它范围更小一些,只能描述对象结构

interfacePosition{x:number;y:number;}

它们写法有一点区别,type 后面需要用 =,interface 后面不需要 =,直接就带上 {。

范围

type 能表示的任何类型组合。

interface 只能表示对象结构的类型。

继承

interface 可以继承(extends)另一个 interface。

下面代码中,Rect 继承了 Shape 的属性,并在该基础上新增了 width 和 height 属性。

interfaceShape{x:number;y:number;}//继承扩展interfaceRectextendsShape{width:number;height:number;}constrect:Rect={x:0,y:0,width:0,height:0};

interface 也可以继承自 type,但只能是对象结构,或多个对象组成交叉类型(&)的 type

再来看看 type 的继承能力。

type 可以通过 & 的写法来继承 type 或 interface,得到一个交叉类型:

typeShape={x:number;y:number;}typeCircle=Shape&{r:number}constcircle:Circle={x:0,y:0,r:8}声明合并

interface 支持声明合并,文件下多个同名的 interface,它们的属性会进行合并

interfacePoint{x:number;}interfacePoint{y:number;}constpoint:Point={x:10,y:30};

需要注意的是,同名属性的不能进行类型覆盖修改,否则编译不通过。比如我先声明属性 x 类型为 number,然后你再声明属性 x 为 string | numebr,就像下面这样,编译器会报错。

interfacePoint{x:number;}interfacePoint{//报错//Property'x'mustbeoftype'number',butherehastype'string|number'.x:string|number;y:number;}

extends 可以将属性的类型进行收窄,比如从 string | number 变成 string。

但声明合并不行,类型必须完全一致。

type 不支持声明合并,一个作用域内不允许有多个同名 type

//报错:Duplicate identifier 'Point'.typePoint={x:number;}//报错:Duplicate identifier 'Point'.typePoint={y:number;}

当然,如果有和 type 同名的 interface,也会报错。

结尾

总结一下,type 和 interface 的不同点有:

  1. type 后面有 =,interface 没有;
  2. type 可以描述任何类型组合,interface 只能描述对象结构;
  3. interface 可以继承自(extends)interface 或对象结构的 type。type 也可以通过 & 做对象结构的继承;
  4. 多次声明的同名 interface 会进行声明合并,type 则不允许多次声明;

大多数情况下,我更推荐使用 interface,因为它扩展起来会更方便,提示也更友好。& 真的很难用。

我是前端西瓜哥。欢迎关注我,学习更多前端知识。

推荐

首页/电脑版/网名
© 2026 NiBaKu.Com All Rights Reserved.