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

117
Vistas
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 Respuestas
Responde la pregunta

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 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