Home > Software design >  TypeScript copy object's properties to create a new object
TypeScript copy object's properties to create a new object

Time:03-08

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

CodePudding user response:

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]
    }
}
  • Related