12

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

5
  • 3
    why do you want to seperate the declaration from the implementation? Commented Mar 30, 2018 at 23:33
  • I don't see any real reason to do this. Having the definition and implementation in two different places creates meaningless indirection, imo. And if it's just a linter error, there's nothing preventing you from actually doing it and disabling the tslint rule Commented Mar 30, 2018 at 23:45
  • @Thomas, I wanna make it look more like in cpp, where you in header keeps definition and in source implementation Commented Mar 31, 2018 at 0:05
  • 3
    C++ works that way so that (in theory) you don't have to recompile files that include the header if the implementation changes but the header (i.e. the interface) doesn't. That's a necessary evil of C++, it certainly isn't a good thing. There simply isn't any reason to do this in JS/TS. Commented Mar 31, 2018 at 0:27
  • TypeScript is not C++. It does not use header files. Commented Apr 6, 2023 at 12:01

1 Answer 1

22

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.