Reputation: 14218
I have the following object:
{
name: 'Jon',
gender: 'male',
secret: 'xxx'
}
and the interface:
interface PublicUserData {
name: string
gender: string
}
Can I somehow iterate all properties of PublicUserData and delete all properties from the other object that are not present in the interface?
I know that I will have to use reflect-metadata to get that info, but I would need some hint on now to point me into the right direction
Upvotes: 1
Views: 2341
Reputation: 21147
This could be accomplished through the use of decorators and reflect-metadata (as you've already noted) but it's important to understand that TS interfaces aren't a JS language feature and therefore offer no ability for reflection. They are completely erased at runtime. You would have to implement it with actual classes instead.
It might be easier for you to just store an array of strings corresponding to the object properties you care about and use the Object.keys family of methods to delete stuff you don't want.
Upvotes: 1
Reputation: 838
Through the interface it will not work, but you can do this:
interface IUserData{
name: string;
gender: string;
secret: string;
}
class PublicUserData {
name: string;
gender: string;
constructor(data: IUserData){
this.name = data.name;
this.gender = data.gender;
}
}
class UserData extends PublicUserData implements IUserData {
secret: string;
constructor(data: IUserData){
super(data);
this.secret = data.secret;
}
}
And so use:
var data = {
name: 'Jon',
gender: 'male',
secret: 'xxx'
} as IUserData;
var publicUserData = new PublicUserData(data);
var userData = new UserData(data);
var publicUserData2 = new PublicUserData(userData);
Result:
publicUserData: {name: "Jon", gender: "male"}
publicUserData2:{name: "Jon", gender: "male"}
userData: {name: "Jon", gender: "male", secret: "xxx"}
Of course to use the boxing/unboxing mechanism through casting types looks better, but this can not hide properties. Therefore, it is necessary to give types explicitly.
Upvotes: 2