如何将Typescript接口实现为es5样式的“类"? [英] How to implement a Typescript interface to an es5-style "class"?

查看:274
本文介绍了如何将Typescript接口实现为es5样式的“类"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以为es6类实现接口的方法非常简单:

The way we can implement an Interface to an es6 class is pretty straightforward:

interface IDog {
    bark(): void
}

class Dog implements IDog {
    bark(): void {

    }
}

问题是:如何为该类"实现相同的接口:

The question is: how to implement the same interface to this "class":

const Dog = function() {

}

Dog.prototype.bark = function() {

}

我尝试将Dog的类型定义为IDog:const Dog: IDog.没用.

I tried defining the type of Dog as IDog: const Dog: IDog. Didn't work.

因此,我需要它来实现依赖倒置,但我不知道如何使用es5类来实现.我看到古典继承样式是Javascript中的反模式",因此我决定以旧的方式创建类,并且需要帮助为它们实现Typescript接口.

So, I need it to implement Dependency Inversion and I can't figure out how to do this with es5 classes. I saw that Classical Inheritance style is an "antipattern" in Javascript, so I decided to create classes the old way and need help implementing Typescript Interfaces to them.

推荐答案

我假设您要使用es5样式的类实现,该实现声明为符合IDog接口,并由编译器进行类型检查以确保它确实符合该界面.

I assume that you want es5-style class implementation, which is declared to conform to IDog interface, and type-checked by the compiler to ensure that it really conforms to that interface.

坏消息-TypeScript不支持.您可以使TypeScript认为es5 Dog是实现IDog的类,但是您必须声明DogConstructor接口,并对Dog使用as any as DogConstructor类型断言.而且您不能使TypeScript对基于原型的实现进行类型检查,因为Object.prototype(随后为Dog.prototype)在系统库中被声明为any(请参见问题进行一些讨论):

Bad news - TypeScript does not support that. You can make TypeScript to think that es5 Dog is a class that implements IDog, but you have to declare DogConstructor interface and use as any as DogConstructor type assertion for Dog. And you can't make TypeScript to typecheck prototype-based implemenation because Object.prototype (and subsequently Dog.prototype) is declared as any in the system library (see these issues for some discussion):

interface IDog {
    bark(): void
}

interface DogConstructor {
    new(): IDog;
}

const Dog = function (this: IDog) {
    // this.bark(); you can do this because of `this: IDog` annotation
} as any as DogConstructor;

Dog.prototype.bark = function() {

}

const p = new Dog();
p.bark();

我认为对此的支持不会得到改善. Es5样式类通常以JavaScript代码实现,而JavaScript代码并不意味着要进行类型检查,而TypeScript为编写允许使用类型安全方式使用javascript实现的类型声明提供了足够的支持.如果要在TypeScript中实现类,则可以简单地使用实际类.

I don't think that support for this will ever be improved. Es5-style classes are usually implemented in javascript code which is not meant to be typechecked, and TypeScript provides enough support for writing type declarations that allow to use javascript implementation in type-safe way. If you are implementing classes in TypeScript, you can simply use real classes.

这篇关于如何将Typescript接口实现为es5样式的“类"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆