gwenoleR
gwenoleR

Reputation: 90

TypeScript: return only a part of the interface

I have an User interface like this

interface IUser {
    name: string,
    phoneNumber: string
}

and a PublicUser interface like this

interface IPublicUser {
   name: string
}

What i'm trying to do it's from an object of type IUser return only public informations.

I tried something like this :

 const user: IUser = {
   name: 'Eliott',
   phoneNumber : '+1...'
}

console.log(user as unknown as  IPublicUser)

But always return the full user.

My temporary fix it's to create a method toPublicJson to return only the desired field, but it's not very good, because if my interface change I must also change this method..

Do you have some advices ?

Thanks

Upvotes: 2

Views: 1116

Answers (1)

Oscar Paz
Oscar Paz

Reputation: 18292

You must remember that TypeScript compiles to JavaScript. Statements like variable as type get lost in transpilation. They are just hints to the transpiler and the user, but they don't really mean anything. In the same way, interfaces are just hints and help for the compiler, by they really meant nothing at runtime.

If you want to do that, you still have to do it by hand, to create another object with the properties you want:

const publicUser : IPublicUser = { name: user.name };

Of course, you may only care about what other programmers see when dealing with your code, so, in that way, they'll just see IPublicUser and if they want to use a property that its not in that interface, they'll get a compiler error. But if you care about what is really happening when the code is executing, then you have to do it explicitly.

Upvotes: 3

Related Questions