首页 > 解决方案 > 如何在打字稿中键入两个对象之间共享相同键的两个对象?

问题描述

编辑:

此问题已被标记为与此问题重复。我在其他问题中看不到任何相关内容。


两个接口IObjectAIObjectB共享相同的键foobar

// 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] =

我希望打字稿理解,如果值为keyis foofunctionFooOrBar则为 type IFunctionFoo

怎么可能做到这一点?

这是codesandbox的复制品

标签: typescript

解决方案


通过添加 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;
}, {});

推荐阅读