【问题标题】:How to populate properties of an object implementing an interface using another object implementing an interface that extends the other? [duplicate]如何使用实现扩展另一个接口的另一个对象来填充实现接口的对象的属性? [复制]
【发布时间】:2022-06-11 00:06:32
【问题描述】:
  interface A { a: string; x?: string }
  interface AB extends A { b: string }

  let a: A = { a : 'initial' }
  let ab: AB = { a: 'alex', b: 'bolbets', x: 'hello world!' };

  a = Object.keys(ab).forEach((key) => if (key in a) a[key] = ab[key])
  // Result: a = { a: 'alex' }
  // Desired output:  a = { a: 'alex', x: 'hello world!' }
  a = ab as A // Or `as A & AB`
  // Result: a = { a: 'alex' b: 'bolbets', x: 'hello world!' }
  // Desired output:  a = { a: 'alex', x: 'hello world!' }

【问题讨论】:

  • 你不能。类型信息在编译时被删除,在运行时不可用。

标签: typescript


猜你喜欢
  • 2016-04-28
  • 2023-02-13
  • 2012-01-18
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 2021-10-28
相关资源
最近更新 更多