Vue wants you to merge the class and interface together, essentially extending the Vue
class with your own properties.
For instance, consider this example:
class Animal {
legs: number;
}
interface Animal {
tail: boolean;
}
Upon creating a new instance of this Animal
object, it will have both legs
and tail
properties.
const animal = new Animal();
animal.legs = 4; // no type error
animal.tail = true; // no type error
However, things get complicated when you attempt to add a method to the interface Animal
, as interfaces are meant for structure and not implementation.
To address this issue, TypeScript provides type augmentation, as mentioned in the linked article.
By importing the Animal
class and declaring a module with the same name, you can combine the two objects:
import Animal from "./animal";
declare module "./animal" {
// Here, you can now add the interface
interface Animal {
tail: boolean;
eat(food: string): void;
}
}
While you still can't implement methods directly in an interface, exposing the object's prototype allows you to include implementation details that were previously inaccessible.
Animal.prototype.eat = function(food) {
// consume `food` and perform action
}
If you didn't encounter an error without the import statement, it's because TypeScript recognized a module named Vue
, and until you access something specific to that import, no error is triggered.