Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define typescript class method

I cannot find any information about "declaration and then initialization" of class method, for example can I do this (code below), first declare getName() and then initialize it, tslint tips me that I cannot do this, then what I should do, if doesn't want construction, like public getName(name: string): string { return this.name }?

class Cat {
  public getName(name: string): string;
  
  constructor() { ... }
  
  getName(name) {
    return this.name;
  }
}
like image 362
Ramazan Chasygov Avatar asked Mar 30 '18 23:03

Ramazan Chasygov


1 Answers

One reason for having separate "declaration and then initialization" is that it helps to separate public interface from private implementation.

In TypeScript, one can do that by using interface as declaration and class as initialization. Also, TypeScript has module system built-in the language, so instead of having some things public and some things private in the class, you can just make the whole class to be a private implementation detail, not exported and not available outside the module:

export interface Cat {
    getName(name: string): string;
}


// NOTE: this whole class is an implementation detail and is not exported
class CatImpl implements Cat {

  name: string;

  constructor() { }


  getName(name: string) {
    return this.name;
  }
}

// this is exported and is publicly available for creating Cats
export function createCat(): Cat {
    return new CatImpl();
}
like image 139
artem Avatar answered Oct 17 '22 02:10

artem