Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Creating model classes in Typescript
- Tip: Recommended way of creating classes that model the data of your Typescript app.
- ## Creating simple classes
- Create a simple class with a small set (0-3) of parameters in the constructor.
- * Define the properties directly in the parameter of the constructor.
- * Define optional parameters by defining default values
- **Defining the class**
- ```
- export class User {
- constructor(
- public username: string, //mandatory property
- public password: string,
- public role: string = 'user' //optional parameter with default value
- ){}
- ```
- **Creating instances**
- ```
- private user1 = new User('killerchip','password','admin');
- private user2 = new User('cioannou','password'); //role will be set to 'user'
- ```
- **An update member function**
- ```
- public update(username?:string, password?:string, role?:string) {
- if (typeof username !== 'undefined') {
- this.username = username;
- }
- if (typeof password !== 'undefined') {
- this.password = password;
- }
- if (typeof role !== 'undefined') {
- this.role = role;
- }
- ```
- ## Classes with many parameters
- In case of many parameters constructor is better to have a parameter object.
- **Define an Interface**
- ```
- export interface PersonInterface {
- firstName: string;
- lastName: string;
- phone?: string;
- email: string;
- address?: string;
- country?: string;
- }
- ```
- **Then define the class**
- ```
- import { PersonInterface } from './person.interface';
- export class Person implements PersonInterface {
- public firstName: string;
- public lastName: string;
- public phone?: string;
- public email: string;
- public address?: string;
- public country?: string = 'Greece'; //default value
- constructor(value: PersonInterface) {
- for (const prop in value) {
- this[prop] = value[prop];
- }
- }
- }
- ```
- **Optionally add update method**
- An `UpdateInterface` will have all properties as optional, to allow updating only a subset of them.
- ```
- export interface PersonUpdateInterface {
- firstName?: string;
- lastName?: string;
- phone?: string;
- email?: string;
- address?: string;
- country?: string;
- }
- ```
- And the method. The method can be used by constructor also.
- ```
- import { PersonUpdateInterface } from './person-update.interface';
- export class Person implements PersonInterface {
- public firstName: string;
- public lastName: string;
- public phone?: string;
- public email: string;
- public address?: string;
- public country?: string = 'Greece';
- constructor(value: PersonInterface) {
- this.update(value);
- }
- public update(value: PersonUpdateInterface){
- for (const prop in value) {
- this[prop] = value[prop];
- }
- }
- }
- ```
Add Comment
Please, Sign In to add comment