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

125
Visualizações
TypeScript copy object's properties to create a new object

I want to create a new object of type 'B' from the object of type 'A' that extends 'B'. I've tried to copy properties of type 'B' from the object with type 'A' and that gives me an error.

Could you please help me to resolve this error or explain what I do wrong. Here is my code example:

interface ThemeMeta {
    available: boolean;
    tags: string[];
}
const defaultThemeMeta: ThemeMeta = {
    available: false,
    tags: []
};

interface Theme extends ThemeMeta {
    name: string;
    domainName: string;
    lastUpdate: number;
    published: boolean;
    developer: boolean;
    pinned: boolean;
    id: number;
}

const defaultTheme:Theme = {
    name: 'Default theme name',
    domainName: '',
    lastUpdate: 0,
    published: false,
    developer: false,
    pinned: false,
    id: 0,
    available: false,
    tags:[]
};

const theme:Theme = defaultTheme,
    themeMeta:ThemeMeta = defaultThemeMeta;
let key: keyof ThemeMeta;
for(key in defaultThemeMeta) {
    themeMeta[key] = theme[key];
}

Playground Link

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Currently type of key if keyof ThemeMeta, which mean theme[key] can be any type of available types of the values of ThemeMeta. in our case is boolean or string[]. so type of keyof ThemeMeta[keyof ThemeMeta] is boolean | string

When you then apply it to any of specific properties of themeMeta you got an error, because neither boolean or string[] cannot accept value of type boolean | string

What you can do is:

const theme:Theme = defaultTheme;
let themeMeta:ThemeMeta = defaultThemeMeta;
let key: keyof ThemeMeta;
for(key in defaultThemeMeta) {
    themeMeta = {
        ...themeMeta,
        [key]: theme[key]
    }
}
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