1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

TypeScript declares properties with the first use so you can not use Object.keys

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.