When use a interface or class in Typescript

Josbel Luna picture Josbel Luna · Aug 7, 2018 · Viewed 34.4k times · Source

I have a simple scenario of a login that requires user's input a email and password in Typescript. I need to create some type to get this strong-typed and send it to the back-end.

Should this be written as:

export interface UserLogin {
  email: string;
  password: string;
}
//OR
export class UserLogin {
  email: string;
  password: string;
}

And how to know when is the scenario to use any of these?

Answer

alephnerd picture alephnerd · Aug 7, 2018

At it's most basic, a class is essentially an object factory (ie. a blueprint of what an object is supposed to look like and then implemented), whereas an interface is a structure used solely for type-checking.

While a class may have initialized properties and methods to help create objects, an interface essentially defines the properties and type an object can have.

In the scenario you described, one would use the interface to set the type for UserLogin.