【发布时间】:2021-03-01 18:14:36
【问题描述】:
编辑:
此问题已被标记为与this one 重复。我在其他问题中没有看到任何相关内容。
IObjectA 和 IObjectB 两个接口共享相同的密钥 foo 和 bar:
// types
interface IObjectFoo { code: number }
interface IObjectBar { name: string }
type IFunctionFoo = () => IObjectFoo
type IFunctionBar = () => IObjectBar
interface IObjectA {
foo: IFunctionFoo
bar: IFunctionBar
}
type IObjectAKeys = keyof IObjectA
interface IObjectB {
foo?: IObjectFoo
bar?: IObjectBar
}
// code
const objectA = {
foo: () => ({ code: 127 }),
bar: () => ({ name: 'Louise Michel' })
} as IObjectA
const someFilter = (obj: string) => ['foo'].includes(obj)
const keys = Object.keys(objectA).filter(someFilter) as IObjectAKeys[]
const objectB = keys.reduce((acc: IObjectB, key) => {
const functionFooOrBar = objectA[key]
// error : Type '{ code: number; } | { name: string; }' is not assignable to type '(IObjectFoo & IObjectBar) | undefined'.
acc[key] = functionFooOrBar()
return acc
}, {})
acc[key] = 出现错误。
我想让 typecript 明白,如果 key 的值是 foo,那么 functionFooOrBar 的类型是 IFunctionFoo。
如何才能做到这一点?
【问题讨论】:
-
通过添加类型断言
acc[key] = functionFooOrBar() as IObjectFoo & IObjectBar;,错误消失了 -
如果你确定
key === 'foo'acc[key as 'foo'] = functionFooOrBar(),你也可以这样做key === 'foo' -
@uranshishko 非常感谢你,这行得通!请用您的第一条评论回答问题。
标签: typescript