Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - How to implement a Typescript interface to an es5-style "class"?

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() {

}

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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();

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...