Skip to content

Instantly share code, notes, and snippets.

@desaroxx
Last active December 21, 2018 18:08
Show Gist options
  • Save desaroxx/a74dd789d14eb6cc59f6 to your computer and use it in GitHub Desktop.
Save desaroxx/a74dd789d14eb6cc59f6 to your computer and use it in GitHub Desktop.
Typescript Models: Interfaces vs Model Classes
/**
* advantages:
* - interface code not compiled
* - faster at runtime (Javascript object only; no prototypes)
*/
interface IServiceCall {
id: string | number;
title: string;
businessPartner: string;
startTime: date;
endtime?: date;
}
const sc1: IServiceCall = {
id: '12312qsasdad',
title: 'Repair Rotor ESX2000',
businessPartner: 'Nestle SA',
startTime: new Date()
};
/**
* advantages:
* - define default values
*/
class ServiceCallModel {
constructor(public id: string | number,
public title: string,
public businessPartner: string,
public startTime: date = new Date(),
public endTime?: date) {}
}
const sc2: ServiceCallModel = new ServiceCallModel('12312qsasdad',
'Repair Rotor ESX2000',
'Nestle SA',
new Date());
@desaroxx
Copy link
Author

  • use interface to create models
  • interface names are CapitalCamelCase and start with the letter I indicating it being an interface
  • if default values are needed during creation, then use factory method pattern

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment