简体   繁体   English

使用接口键入 class?

[英]Typing a class with an interface?

Ive been creating my classes like this:我一直在创建这样的课程:

interface ICar {
  wheels: number;
  model: string;
  drive?: () => void;
}

const Car = function(c: ICar) {
  this.wheels = c.wheels
  this.model = c.model
  this.drive = function() {
    console.log(this.model) // <-- this doesnt autocomplete when typing `this.`
  }
}

A small problem im having is that referencing this within the class doesn't show autocompletion which is making me make some small mistakes in my much larger classes.我遇到的一个小问题是,在 class 中引用this并没有显示自动完成功能,这让我在更大的课程中犯了一些小错误。

I instead can make a class like this:相反,我可以像这样制作 class :

interface ICar {
  wheels: number;
  model: string;
  drive: () => void;
}

class Car {
  wheels: number;
  model: string;
  drive: () => void;

  constructor(obj: ICar) {
    this.wheels = obj.wheels;
    this.model = obj.model;
    this.drive = function() {
      console.log(this.model) // this provides autocompletion and type checking
    }
  }
}

However, with this, I feel like there is a lot of repetition of code.但是,有了这个,我觉得有很多重复的代码。 I dont like how I define the interface ICar and then i have to essentially repeat the code within the class.我不喜欢如何定义接口ICar ,然后我必须在 class 中重复代码。

I thought using implements would fix it eg: class Car implements ICar but that doesnt work either.我认为使用implements可以解决它,例如: class Car implements ICar ,但这也不起作用。

Is there something im missing or am I doing this wrong?我有什么遗漏或者我做错了吗?

You can actually specify the type of "this" since Typescript 2.0.从 Typescript 2.0 起,您实际上可以指定“this”的类型 That should help you get the correct type for the "this" keyword.这应该可以帮助您获得“this”关键字的正确类型。

Using your example:使用您的示例:

interface ICar {
  wheels: number;
  model: string;
  drive?: () => void;
}

const Car = function(this: ICar, c: ICar) {
  // Now the type of "this" should be `ICar`
  this.wheels = c.wheels
  this.model = c.model
  this.drive = function() {
    console.log(this.model)
  }
}

You're editor isn't up to much if it can't spot the class members.如果您无法发现 class 成员,那么您的编辑就不能胜任。

You may want to use an abstract class and extend it, also setting the access scope will auto set the member for you:您可能想要使用抽象 class 并对其进行扩展,同时设置访问 scope 将自动为您设置成员:

abstract class Car {
    abstract wheels: number
    abstract model: string;
    abstract drive(): void;
}

class MyCar extends Car {
    constructor(public wheels: number, public model: string) {
        super()
    }
    drive() { }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM