简体   繁体   English

如何通过删除属性将接口A的object转换为接口B

[英]How to convert from object from interface A to interface B by deleting property

Assuming I have two interfaces:假设我有两个接口:

interface A {
  a: string;
  b: string;
  x: string;
}

interface B {
  a: string;
  b: string;
}

When I have an object implementing interface A and I want to drop the property x (and the object implements interface B afterwards) - how do I tell TS what I am trying to do?当我有一个实现接口A的 object 并且我想删除属性x (并且 object 之后实现接口B )时 - 我如何告诉 TS 我要做什么? Just executing delete obj.x;只需执行delete obj.x; on the object causes TS to complain, because x is required from interface A .在 object 上会导致 TS 抱怨,因为接口A需要x

This is how I'd have done that.我就是这样做的。

interface A {
  a: string;
  b: string;
  x: string;
}

interface B {
  a: string;
  b: string;
}

function convertAtoB(a: A) {
  delete (a as any).x;
  return a as B;
}

You can use Omit or make property an optional您可以使用Omit或将属性设为可选

interface A {
  a: string;
  b: string;
  x: string;
}

interface A1 {
  a: string;
  b: string;
  x?: string;

}

const result: Omit<A, 'x'> = { a: 'a', b: 'b' }
const result1: A1 = { a: 'a', b: 'b' }

It is considered a bad practive to use delete .使用delete被认为是一种不好的做法。

Please consider next type safe example to remove object property请考虑下一个安全示例以删除 object 属性

const removeProperty = <T, P extends keyof T>(obj: T, prop: P): Pick<T, Exclude<keyof T, P>> => {
  const { [prop]: _, ...rest } = obj;
  return rest
}

const result2 = removeProperty({ age: 2, name: 'John' }, 'name') // { age: 2 }

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

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