简体   繁体   中英

Typescript removing other properties from object with “as”?

I want to send an object via JSON, which implements an interface, but also has some other properties that I don't want to send. How can I "remove" everything else so I have a pure object with only the interface properties?

Example:

interface IBlock{
  x:number;
  y:number;
}

class Block implements IBlock{
  public z:number;
}
...
send(JSON.stringify(new Block() as IBlock));

responseIWant = "{x:0,y:0}";
responseIGet = "{x:0,y:0,z:0}";

Both interfaces and casting using as are compile time constructs that don't do anything at runtime when the code is actually executed.

You could use the pick method from lodash :

const subset = _.pick(obj, ['x', 'y'])

Or if you don't want to bring in a library you could do this with destructuring:

const subset = (({ x, y }) => ({ x, y }))(obj);

Another more advanced technique would be using actual classes with reflect-metadata and decorators to be able to make better decisions about the content of your code at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM