As you know, in Typescript one might use JS classes as interfaces.
interface Post {
title: string;
}
class Post {
title: string;
}
What are the advantages of using classes (if any) instead of interfaces?
As you know, in Typescript one might use JS classes as interfaces.
interface Post {
title: string;
}
class Post {
title: string;
}
What are the advantages of using classes (if any) instead of interfaces?
For further actions, you may consider blocking this person and/or reporting abuse
Prince -
chintanonweb -
thinkThroo -
Ellis -
Top comments (3)
Usually in Typescript, interfaces are used to describe the structure of an object, just as in your example.
class
es usually contain actual behaviour code in them. In default configuration (strict: true
), Typescript will complain aboutwith the following error message:
Additionally,
interface
s are purely used in type-checking, since they don't exist in Javascript - they don't get any compilation output! If you create apost.ts
file and fill it with your example code from above, your compiledpost.js
file will only containClass has runtime representation whereas interface hasn't. It means that when you make a Class you get type + value constructor by "new" keyword. In other hand when you make an interface you have type but no value constructor, so you need to make the value separately.
They are the same thing except in a class you can provide values to properties and write functions.