Friend Class in TypeScript

In C ++, there is something called a class of friends. As far as I know, TypeScript / JavaScript does not have such a thing. Is there a way to simulate this behavior of the friend class in TypeScript / JavaScript?

To give a better context (if necessary) to why and what I'm trying to do, I make a little game for fun (and study the material) and try to do it . At the moment, I just use public methods, and everything works, but I would like to limit the availability of these methods to only one other class. I use TypeScript if this helps.

+4
source share
2 answers

TypeScript offers and access modifiers. Currently it does not have something like or . protectedprivatefriendinternal


To get similar effects: if you pack your code as a library and issue declaration files for it .d.ts, you can use the /** @internal */JSDoc annotation for properties that you do not want to use by outsiders, and also specify the --stripInternal compiler option . This will force the exported declaration to leave these properties.


Another way to do something like this is to create a public interfaceone that implements your class, and then export only the class as a public interface. For instance:

// public interfaces
export interface UnitStatic {
  new(grid: Grid, x: number, y: number): Unit;
}
export interface Unit {
  move(x: number, y: number): void;
}
export interface GridStatic {
  new(): Grid;
  NUM_CELLS: number;
  CELL_SIZE: number; 
}
export interface Grid {
  // public methods on Grid
}

// private implementations
class UnitImpl implements Unit {
  constructor(private grid: GridImpl, private x: number, private y: number) {

  }
  move(x: number, y: number) {
    // ...
  }
}

class GridImpl implements Grid {
  cells: Unit[][] = [];
  constructor() {
    // ...
  }
  static NUM_CELLS = 10;
  static CELL_SIZE = 20;
}

//public exports
export const Unit: UnitStatic = UnitImpl;
export const Grid: GridStatic = GridImpl;

This is tedious, but it makes it very clear which parts of your code are for outsiders and which are not.


, / JavaScript , IIFE . TypeScript, , , , .


, . , . !

+5

, , . . https://github.com/Microsoft/TypeScript/issues/2136.

TypeScript ++ Java. , TypeScript ( ES6) , , , .

, , , , JS/TS , .

-1

Source: https://habr.com/ru/post/1684323/


All Articles