简体   繁体   中英

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? Just executing delete obj.x; on the object causes TS to complain, because x is required from interface A .

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

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 .

Please consider next type safe example to remove object property

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 }

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