Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda