繁体   English   中英

Typescript用“ as”从对象中删除其他属性?

[英]Typescript removing other properties from object with “as”?

我想通过JSON发送对象,该对象实现了一个接口,但是还具有其他一些我不想发送的属性。 如何才能“删除”其他所有内容,以便我只有接口属性的纯对象?

例:

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}";

interfaces和使用as强制转换都是编译时构造,在实际执行代码时,它们在运行时不执行任何操作。

您可以使用lodashpick方法:

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

或者,如果您不想引入一个库,则可以通过解构来实现:

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

另一种更高级的技术是将实际类与reflect-metadata和修饰符一起使用,以便能够在运行时对代码内容做出更好的决策。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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