【发布时间】: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