I'm having the following interfaces:
export interface ObjectX {
key: string,
title: string,
data: Record<string, unknown>;
}
export interface ObjectY {
name: string,
security: number,
integrity: number,
}
And then the objects:
const objectX: ObjectX = {
key: 'generic_data',
title: 'Generic Data',
data: {
name: 'Generic Data',
security: 50,
integrity: 10,
},
}
let objectY: ObjectY = {
name: 'Specific Data',
security: 10,
integrity: 25,
}
Now, if I want to set the ObjectY with ObjectX data, I've to do the following:
objectY = objectX.data as any
Note: not always objectX.data === ObjectY Interface, I want to set like a dynamic type that adapts to current object properties.
I'd like to achieve this as long as objectY and ObjectX.data have the same properties:
objectY = objectX.data
Is it possible just with an interface?? Thank you very much in advantage
CodePudding user response:
You can make ObjectX a generic type
export interface ObjectX<TData> {
key: string,
title: string,
data: TData;
}
This way you can use it with any type:
export interface ObjectY {
name: string,
security: number,
integrity: number,
}
let myXObject: ObjectX<ObjectY>;
let myYObject: ObjectY = myXObject.data;