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

130
Visualizações
TypeScript create new interface from existing interface and change type of all properties
interface UserFlags {
  isDev: boolean;
  isAdmin: boolean;
  isMod: boolean;
}

const flagPositions: FlagPositions<UserFlags> = {
  isDev: 0,
  isAdmin: 1,
  isMod: 2,
};

How would you implement FlagPositions so that it takes 1 generic parameter to an interface with type { [name: string]: boolean } and require all the properties of the interface to be present in the new interface but be of type number?

I tried various methods using keyof but none worked.

Edit: I got this working after posting but I would like it to be an interface

type FlagPositions<F> = {
  [K in keyof Required<F>]: number;
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You want FlagPositions<T> to be a mapped type whose keys are the same as keyof T but whose values are number. You can write that like this:

type FlagPositions<T> = { [K in keyof T]: number };

And verify that it works as you want:

const flagPositions: FlagPositions<UserFlags> = {
    isDev: 0,
    isAdmin: 1,
    isMod: 2,
};

Note that it is not necessary to constrain T to {[name: string]: boolean} or Record<keyof T, boolean>, but you can do so if you want:

type FlagPositions<T extends Record<keyof T, boolean>> =
    { [K in keyof T]: number };


declare const oops: FlagPositions<{ a: number }>; // error!
// ---------------------------->  ~~~~~~~~~~~~~
//   Types of property 'a' are incompatible.

You can't make FlagPositions<T> an interface because interfaces need to have keys known at compile time, and T is generic and can have all sorts of keys. But once you have the FlagPositions<UserFlags> type which has known keys (they are isDev, isAdmin, and isMod), then you can make an interface extend that:

interface UserFlagPositions extends FlagPositions<UserFlags> { }

const u: UserFlagPositions = {
    isDev: 2,
    isAdmin: 1,
    isMod: 0
}

Playground link to code

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