Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
How can I restrict keys in the used type?

I write a library

type State = {
  playing: boolean
  phases: {
    [key: string]: {
      progress: number
    }
  }
}

class BaseWidget {
  state: State

  constructor() {
    this.state = {
      playing: false,
      phases: {},
    }
  }
}

I use it like this

class Widget extends BaseWidget {
    constructor() {
        super()
        this.state.phases = {
            start: {
                progress: 0,
            },
            finish: {
                progress: 0,
            },
        }
    }
}

Different classes of inherited BaseWidget have different phases
How can I specify that this Widget class will only have a start and a finish?
Is it possible to somehow clarify the State type from the Widget class?
Or maybe I need to use generics?
Maybe I need to use not [key: string], but [key in keyof T]? But how do I pass T? What is the correct syntax?
Thanks!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your question is a bit broad, but looking at what you're trying to achieve, I would create something like this:

type State = Record<string, any>;

class BaseWidget<S extends State> {
  state: S;

  constructor(initState: S) {
    this.state = initState;
  }
}

interface HasStartPhase {
  start: {
    progress: number;
  };
}

interface HasFinishPhase {
  finish: {
    progress: number;
    extraInfo: string;
  };
}

interface WidgetState extends State {
  playing: boolean;
  phases: HasStartPhase & HasFinishPhase;
}

class Widget extends BaseWidget<WidgetState> {
  constructor() {
    super({
      playing: false,
      phases: {
        start: {
          progress: 0
        },
        finish: {
          progress: 0,
          extraInfo: "abc"
        }
      }
    });
  }
}

It allows any state in your BaseWidget, and specific Widgets can specify their own State shape. Creating interfaces for the Phases allows you to mix and match them when they are needed.

Here is a TS Playground for you to try it out.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can't use an index signature to restrict the type of the keys, but you can use the Record utility type to get the same result. Because you're initializing phases with {} initially, you'll need to make it a Partial<Record<...>>:

type State<T extends string> = {
  playing: boolean
  phases: Partial<Record<T, {
    progress: number
  }>>
}

class BaseWidget<T extends string> {
  state: State<T>

  constructor() {
    this.state = {
      playing: false,
      phases: {},
    }
  }
}

type WidgetPhase = 'start' | 'finish'

class Widget extends BaseWidget<WidgetPhase> {
    constructor() {
        super()
        this.state.phases = {
            start: {
                progress: 0,
            },
            finish: {
                progress: 0,
            },
            nonexistent: { // Compile error!
                progress: 0,
            }
        }
    }
}

playground link

If you don't actually want it to be Partial, you can initialize it through the constructor of the base class; this guarantees that all keys are always present:

type Phase = {
    progress: number
}

type State<T extends string> = {
  playing: boolean
  phases: Record<T, Phase>
}

class BaseWidget<T extends string> {
  state: State<T>

  constructor(phases: Record<T, Phase>) {
    this.state = {
      playing: false,
      phases: phases,
    }
  }
}

type WidgetPhase = 'start' | 'finish'

class Widget extends BaseWidget<WidgetPhase> {
    constructor() {
        super({
            start: {
                progress: 0,
            },
            finish: {
                progress: 0,
            },
        })
    }
}

playground link

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda