typescript - 如何通过删除属性将对象从接口(interface)A转换为接口(interface)B

标签 typescript

假设我有两个接口(interface):

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

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

当我有一个实现接口(interface) A 的对象并且我想删除属性 x (并且该对象随后实现接口(interface) B) -我如何告诉 TS 我想要做什么?仅在对象上执行 delete obj.x; 就会导致 TS 提示,因为接口(interface) 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;
}

关于typescript - 如何通过删除属性将对象从接口(interface)A转换为接口(interface)B,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65224086/

相关文章:

javascript - 在 Angular 5 中隐藏 ngFor 的一部分

javascript - Typescript 错误 : Map. values() 给出 IterableIterator not Iterable

javascript - 只订阅一次多个 FormControl

unit-testing - 类型错误 : Cannot read property 'injector' of null after upgrading to Angular 2. 0 最终

reactjs - 如何为无状态 React 组件创建 TypeScript 类型定义?

Typescript 属性 'style' 在类型 'HTMLElement' 上不存在

javascript - 删除搜索栏中的搜索词时,搜索功能不起作用

angular - Httpclient Angular 教程

node.js - Express TypeScript 路由属性

typescript - 为什么 typescript 抛出错误信息 : Property does not exist on type?