Búsqueda de sitios web

Cómo declarar un tipo para todos los métodos de una clase en TypeScript


Quiero forzar a que todos los métodos devuelvan el mismo tipo.

Así:

interface ITextGenerator {
  [key: string]: () => string
}

class TextGenerator implements ITextGenerator {
  genarator1 = () => "text1"

  genarator2 = () => "text2
}

Error en TextGenerator:

La clase 'TextGenerator' implementa incorrectamente la interfaz 'ITextGenerator'. Falta la firma de índice en el tipo 'TextGenerator'.

Respuesta #1

Puedes hacer lo siguiente para que funcione:

interface ITextGenerator {
  [key: string]:  () => string;
}

class TextGenerator implements ITextGenerator{

  [key: string]:  () => string; // This is important but i think kinda redundant

  test = () => '33'; // this is fine
  error = 33; // this is not okay
}

En realidad no sé la razón por la cual esto es necesario, así que si lo averiguas, avísame.