本文介绍了打字稿,使用没有构造函数的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Angular网站上的英雄之旅教程时,我发现了以下语法(不久):

While working with the "Tour of Heroes" tutorial on the Angular website I found the following syntax (shortly):

class Hero {
  id: number,
  name: string,
}

const aHero: Hero = {
  id: 1,
  name: 'Superman'
}

console.log(aHero instanceof Hero); //false

这样做有什么意义?如果我检查aHero的类型,它只是一个常见的对象而不是英雄类型。用构造函数初始化一个对象会更好吗?:

What would be the point in doing this? when if I check the type of "aHero", it is only a common object and not a "Hero" type. Would it be better just initializing an object with a constructor?:

class Hero {
  constructor(id: number, name: string) {}
}


推荐答案

您可以使用类作为您使用它的方式。因此,无论Hero是接口还是类,它都无关紧要,因为你将它用作类型。

You can use class as a type which is the way you're using it. So, whether Hero is an interface or class it doesn't matter because you're using it as a type.

class Hero { id: number; name: string }

interface Hero { id: number; name: string }

以下不涉及Hero是类还是接口

The following doesn't concern whether Hero is a class or interface

let hero: Hero = { id: 1, name: 'me' }

其中接口区别为 interface 仅适用于您,它不会被转换为javascript。一个,你不能一个接口

Where interface and class differentiate is interface is only for you, it doesn't get transpiled into javascript. A class does and you cannot new an interface.

构造函数或没有构造函数,如果你 new 那么它是 instanceof 。再试一次

Constructor or no Constructor, if you new it then it is an instanceof. Try it again with this

let hero = new Hero();

您的 instanceof 日志将是 true 因为您确实使用关键字 new 创建了Hero实例。

Your instanceof log will be true because you did create an instance of Hero with the key word new.

这篇关于打字稿,使用没有构造函数的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:08