type和之间有什么区别class?
type Point {
x: number, y: number
}
let p = new Point();
Run Code Online (Sandbox Code Playgroud)
以上结果如下:
'Point'仅指类型,但在此处用作值.
为什么会这样?我当然不是Point用作值而是用它来实例化一个类型.
我需要使用哪些情况type因为class不合适?
Tit*_*mir 13
Typescript有两个不同的宇宙在某些点上接触:值空间和类型空间.类型空间是定义类型的位置,类型将被完全擦除,并且在运行时不存在.值空间包含值,显然在运行时存在.
什么是价值?值文字,变量,常量和参数显然是值.函数和类声明也是值,因为它们具有备份它们的运行时对象,即函数对象和类构造函数(也是函数).枚举也是值,因为它们在运行时由对象备份.
什么是类型?任何带有type关键字的定义都是类型,接口,类声明和枚举
你会注意到我在两个空格中提到了类声明.类存在于类型空间和值空间中.这就是为什么我们可以在类型注释(let foo: ClassName)和表达式(ex new ClassName())中使用它们.
枚举也跨越两个世界,它们也代表我们可以在注释中使用的类型,但也代表将保存枚举的运行时对象.
类型空间和值空间中的名称不会发生冲突,这就是我们可以定义具有相同名称的类型和变量的原因:
type Foo = { type: true }
var Foo = { value : true } // No error, no relation to Foo just have the same name in value space
Run Code Online (Sandbox Code Playgroud)
类声明和枚举,因为它们跨越两个空格将在两个空格中"使用"该名称,因此我们无法定义与类声明或枚举具有相同名称的变量或类型(尽管我们可以合并但是是一个不同的概念)
在您的特定情况下,Point它只是一种类型,我们可以在类型注释中使用,而不是我们可以在需要运行时存在的表达式中使用的类型.在这种情况下,类型很有用,因为它允许编译器在结构上检查对象文字是否可分配给Point类型:
let p: Point = { x: 10, y: 15 }; // OK
let p: Point = { x: 10, y: 15, z: 10 }; // Error
Run Code Online (Sandbox Code Playgroud)
如果要创建类,则需要使用class关键字来执行此操作,因为这将创建不仅仅是类型的运行时值:
class Point{
constructor(public x: number, public y: number){}
}
let p = new Point(10,10)
Run Code Online (Sandbox Code Playgroud)
Sef*_*efe 10
您使用 a type(或在其他情况下使用 an interface)作为类型注释来指示 JavaScript 对象的结构:
type Point = {
x: number, y: number
}
function doSomething(p: Point) {
}
let p: Point = { x: 10, y: 15 };
doSomething(p);
Run Code Online (Sandbox Code Playgroud)
这些类型注释受结构类型的约束,这意味着在这种特定情况下,您可以删除类型注释:
let p = { x: number, y: number };
doSomething(p);
Run Code Online (Sandbox Code Playgroud)
类是完全不同的东西,它为您提供了一种更优雅的替代 JS 原型继承的方法:
class Point {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
public move(deltaX: number, deltaY: number) {
this.x = this.x + deltaX;
this.y = this.y + deltaY;
}
}
let p = new Point(10, 15);
p.move(1, 2);
Run Code Online (Sandbox Code Playgroud)
当您查看生成的 JS 代码时,您会很快注意到不同之处:
为了更好地理解,我为所有差异创建了一个表格:
| Description | Type | Interface |
|---------------------------------------------------------|------|-----------|
| Describe functions | ? | ? |
| Describe constructors | ? | ? |
| Describe tuples | ? | ? |
| Interfaces can extend | ? | ? |
| Classes can extend | ? | ? |
| Classes can implement | ? | ? |
| Divide another one of its own kind | ? | ? |
| Create a union with another one of its own kind | ? | ? |
| Be used to create mapped types | ? | ? |
| Be mapped over with mapped types | ? | ? |
| Expands in error messages and logs | ? | ? |
| Be completed | ? | ? |
| Be recursive | ? | ? |
Run Code Online (Sandbox Code Playgroud)
Hint: `?` means partially
Run Code Online (Sandbox Code Playgroud)
也许对于新版本的TypeScript,此表有一些更改,如果有请通过编辑当前帖子来修复该表。
| 归档时间: |
|
| 查看次数: |
1585 次 |
| 最近记录: |