typescript - 如何在打字稿中键入两个对象之间共享相同键的两个对象?
问题描述
编辑:
此问题已被标记为与此问题重复。我在其他问题中看不到任何相关内容。
两个接口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] =
。
我希望打字稿理解,如果值为key
is foo
,functionFooOrBar
则为 type IFunctionFoo
。
怎么可能做到这一点?
解决方案
通过添加 type asertion acc[key] = functionFooOrBar() as IObjectFoo & IObjectBar; 我得到了消失的错误。
你也可以做 const functionFooOrBar = objectA[key as 'foo']; acc[key as 'foo'] = functionFooOrBar() 如果你确定 key === 'foo'
这样做也有效
const objectB = keys.reduce((acc: IObjectB, key) => {
let functionFooOrBar;
if(key === 'foo') {
functionFooOrBar = objectA[key];
acc[key] = functionFooOrBar();
}
return acc;
}, {});
推荐阅读
- c# - 为什么我的应用程序无法通过集成网络摄像头检测到二维码?
- json - 在flutter中显示POST请求的结果
- sql - 合并包含由 ColumnA 的下一个结果预测的 ColumnA 的行
- excel - 错误 - 运行时错误 13. 如何将行数加起来?
- sql - 如何从表中获取相关的源和目的地航班
- laravel - 如何禁用 Laravel 调度程序日志
- jmeter - 无法使用 Jmeter 上传 csv 文件
- c# - c# AsyncSockets 从客户端套接字读取时递归
- php - 如何修改此 Laravel AuthController 登录功能以检查活动列是否为 0?
- elasticsearch - 如何修复“无法导入索引模式”