Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  13] [ 6]  / answers: 1 / hits: 26150  / 6 Years ago, fri, march 30, 2018, 12:00:00

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




More From » typescript

 Answers
45

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

[#54810] Tuesday, March 27, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristani

Total Points: 318
Total Questions: 95
Total Answers: 106

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;