When should we use classes and interfaces? If you want to create and pass a type-checked class object, you should use TypeScript classes. If you need to work without creating an object, an interface is best for you.
The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript. A model, and namely a class, is an actual JS function which is being used to generate new objects.
Hence interface works better when using objects and method objects. Therefore it is our choice to choose between types or interface according to the program needs. In Typescript, union types can contain one or more types using the “ | ” keyword, where we can have a new union type by combining two interfaces.
One of the primary uses of the model in an MVC application is to provide the data displayed in the view and implement the functions invoked from the view. In an AngularJS application the data binding statements are evaluated against the current scope.
Interfaces are only at compile time. This allows only you to check that the expected data received follows a particular structure. For this you can cast your content to this interface:
this.http.get('...')
.map(res => <Product[]>res.json());
See these questions:
You can do something similar with class but the main differences with class are that they are present at runtime (constructor function) and you can define methods in them with processing. But, in this case, you need to instantiate objects to be able to use them:
this.http.get('...')
.map(res => {
var data = res.json();
return data.map(d => {
return new Product(d.productNumber,
d.productName, d.productDescription);
});
});
The Interface describes either a contract for a class or a new type. It is a pure Typescript element, so it doesn't affect Javascript.
A model, and namely a class, is an actual JS function which is being used to generate new objects.
I want to load JSON data from a URL and bind to the Interface/Model.
Go for a model, otherwise it will still be JSON in your Javascript.
I personally use interfaces for my models, There hoewver are 3 schools regarding this question, and choosing one is most often based on your requirements:
interface
is a virtual structure that only exists within the context of TypeScript. The TypeScript compiler uses interfaces solely for type-checking purposes. Once your code is transpiled to its target language, it will be stripped from its interfaces - JavaScript isn’t typed.
interface User {
id: number;
username: string;
}
// inheritance
interface UserDetails extends User {
birthdate: Date;
biography?: string; // use the '?' annotation to mark this property as optionnal
}
Mapping server response to an interface
is straight forward if you are using HttpClient
from HttpClientModule
if you are using Angular 4.3.x and above.
getUsers() :Observable<User[]> {
return this.http.get<User[]>(url); // no need for '.map((res: Response) => res.json())'
}
when to use interfaces:
let instance: FooInterface = { ... };
, you risk having semi-instances all over the place.A class
defines the blueprints of an object. They express the logic, methods, and properties these objects will inherit.
class User {
id: number;
username: string;
constructor(id :number, username: string) {
this.id = id;
this.username = username.replace(/^\s+|\s+$/g, ''); // trim whitespaces and new lines
}
}
// inheritance
class UserDetails extends User {
birthdate: Date;
biography?: string;
constructor(id :number, username: string, birthdate:Date, biography? :string ) {
super(id,username);
this.birthdate = ...;
}
}
when to use classes:
With the latest versions of typescript, interfaces and types becoming more similar.
types
do not express logic or state inside your application. It is best to use types when you want to describe some form of information. They can describe varying shapes of data, ranging from simple constructs like strings, arrays, and objects.
Like interfaces, types are only virtual structures that don't transpile to any javascript, they just help the compiler making our life easier.
type User = {
id: number;
username: string;
}
// inheritance
type UserDetails = User & {
birthDate :Date;
biography?:string;
}
when to use types:
As @ThierryTemplier said for receiving data from server and also transmitting model between components (to keep intellisense list and make design time error), it's fine to use interface but I think for sending data to server (DTOs) it's better to use class to take advantages of auto mapping DTO from model.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With