Rami Chasygov
Rami Chasygov

Reputation: 2784

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;
  }
}

Upvotes: 12

Views: 38545

Answers (2)

Eduard Kolosovskyi
Eduard Kolosovskyi

Reputation: 1584

Alternative solution:

class Cat {
    getName: () => void;
}

Upvotes: 1

artem
artem

Reputation: 51769

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();
}

Upvotes: 19

Related Questions