Reputation: 3
When I do something like that
interface MyInterface {
myStringProperty: string = 'str';
myNumberProperty?: number = 9;
myMethodProperty(): void
}
I had error like: Error image
Based on this article (https://areknawo.com/typescript-introduction-pt2/)
How I can fix it?
Upvotes: 0
Views: 91
Reputation: 383
Please read the official documentation first: https://www.typescriptlang.org/docs/handbook/interfaces.html
If you need default values you have to define a class that implements that interface:
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
constructor(h: number, m: number) { }
}
Upvotes: 2
Reputation: 704
I'm not sure if the author of the article tried his own code in a playground at least. Official 3.7.2 playground doesn't support it (Playground Link).
It's kinda obvious that it shouldn't work since interfaces aren't for defining values, they are for defining contracts. They help you (and the compiler) wiith type checking but they aren't adding or changing fields of objects that are declared as implementations.
Upvotes: 2