In TypeScript, when creating .d.ts source declaration files, which is preferable and why?
declare class Example {
public Method(): void;
}
declare and interface in TS:declare:
declare class Example {
public Method(): void;
}
In the above code declare lets the TS compiler know that somewhere the class Example is declared. This does not mean that the class is magically included. You as a programmer are responsible for having the class available when you are declaring it (with the declare keyword).
interface:
interface Example {
Method(): void;
}
An interface is a virtual construct that only exists within typescript. The typescript compiler uses it for the sole purpose of type checking. When the code is compiled to javascript this whole construct will be stripped out. The typescript compiler uses interfaces in order to check if objects have the right structure.
For example when we have the following interface:
interface test {
foo: number,
bar: string,
}
The objects which we define which have this interface type need to match the interface exactly:
// perfect match has all the properties with the right types, TS compiler will not complain.
const obj1: test = {
foo: 5,
bar: 'hey',
}