【问题标题】:How to type two objects that share the same keys between two objects in typescript? [duplicate]如何在打字稿中键入两个对象之间共享相同键的两个对象? [复制]
【发布时间】:2021-03-01 18:14:36
【问题描述】:

编辑:

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


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] = 出现错误。

我想让 typecript 明白,如果 key 的值是 foo,那么 functionFooOrBar 的类型是 IFunctionFoo

如何才能做到这一点?

这里是the repro on codesandbox

【问题讨论】:

  • 通过添加类型断言acc[key] = functionFooOrBar() as IObjectFoo & IObjectBar;,错误消失了
  • 如果你确定key === 'foo'acc[key as 'foo'] = functionFooOrBar(),你也可以这样做key === 'foo'
  • @uranshishko 非常感谢你,这行得通!请用您的第一条评论回答问题。

标签: typescript


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多