簡體   English   中英

如何通過刪除屬性將接口A的object轉換為接口B

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

假設我有兩個接口:

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

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

當我有一個實現接口A的 object 並且我想刪除屬性x (並且 object 之后實現接口B )時 - 我如何告訴 TS 我要做什么? 只需執行delete obj.x; 在 object 上會導致 TS 抱怨,因為接口A需要x

我就是這樣做的。

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

您可以使用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' }

使用delete被認為是一種不好的做法。

請考慮下一個安全示例以刪除 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