When we program with Typescript, we have a concept that doesn't exist in Javascript: interfaces. In ES6 there are classes, which are syntactic sugar for classical prototyping, but no variable typing and nothing resembling an interface.
One may think that interfaces are the same as in Java or C#, but I have come across this:
class MiClase {
constructor( public atributoA: string) {}
metodoA() {
//hace algo
}
}
interface MiInterfaz extends MiClase {
algo: any;
}
function miFuncion(attr: MiClase) {
console.log(attr instanceof MiClase);
}
function miFuncion2(attr: MiInterfaz) {
console.log(attr instanceof MiClase);
}
let a = {
atributoA: 'hola',
atributoB: 6,
metodoA: function () { },
};
miFuncion(a); //false
miFuncion2(a);//false
let b = new MiClase('Una auténtica instancia de MiClase');
miFuncion(b); //true
miFuncion2(b);//compilador marca error, no cumple la interfaz
What's going on here?
- Why does
a
it not give an errormiFuncion
when it is clearly not of the classMiClase
? - Why are they interchangeable? The interface extends a class and doesn't give an error!
a
is an anonymous object so it will never be the instance of the typeMiClase
.If you try it in javascript you will see that it also returns
false
:Typescript's type checker focuses on how the value/object is defined , not its type. This is called duck typing . Hence, in this case the compiler does not throw you any error:
According to the documentation :
Like
a
if you have the properties required by the interface/classMiClase
, the compiler allows you to.As already mentioned, typescript is not focused on the type, but on the way the type is defined, so when an interface extends a class you are simply adding to the interface the form of the class it inherits.
In summary, to know when to use an interface or class, the same principles as always are used and thus avoid confusion: