Check this code:
interface MyInterface1 {
field1: string;
field2: string;
}
interface MyInterface2 {
field3: string;
field4: string;
}
let o1 = {
field1: "field1",
field2: "field2",
fieldN: "fieldN"
} as MyInterface1;
let o2 = {
field3: "field3",
field4: "field4",
fieldN: "fieldN"
} as MyInterface2;
It compiles to:
var o1 = {
field1: "field1",
field2: "field2",
fieldN: "fieldN"
};
var o2 = {
field3: "field3",
field4: "field4",
fieldN: "fieldN"
};
( code on the playground )
So, you can see that the interfaces do not exist in the compiled (js) code, so you have no way to find out (at runtime) which properties you need to save.
What can you do:
let myInterface1Keys = ["field1", "field2"];
interface MyInterface1 {
field1: string;
field2: string;
}
let o1 = {
field1: "field1",
field2: "field2",
fieldN: "fieldN"
} as MyInterface1;
let persistableO1 = {} as MyInterface1;
Object.keys(o1).forEach(key => {
if (myInterface1Keys.indexOf(key) >= 0) {
persistableO1[key] = o1[key];
}
});
( code on the playground )
source
share