【发布时间】:2021-08-25 09:45:01
【问题描述】:
为什么这段代码无法编译?
type A = { n: number }
type B = { s: string }
type Thing = {
a: A
b: B
}
function update(obj: Thing, path: keyof Thing) {
obj[path] = obj[path]
}
我希望分配的双方都具有A | B 类型,但 TypeScript 编译器失败:
error TS2322: Type 'A | B' is not assignable to type 'A & B'.
Type 'A' is not assignable to type 'A & B'.
Property 's' is missing in type 'A' but required in type 'B'.
10 obj[path] = obj[path]
~~~~~~~~~
有没有办法让它工作?
【问题讨论】:
标签: typescript static-typing union-types