使用映射创建具有不同键的对象数组时出现打字稿错误

问题描述 投票:0回答:1

我正在尝试动态创建对象数组。这些对象可能包含不同的键,但它们始终遵循相同的格式(例如在

myType
上定义)。然而,这样做时,Typescript 会出错。这是一个最小的例子。

type myType = {
  [key: string]: number;
};

const doesNotComplain: myType[] = [{ a: 1 }, { b: 2 }];

const doesComplain: myType[] = [1, 0, 0, 0, 1, 0].map((e) => {
  if (e == 1) return { a: 1 };
  return { b: 2 };
});

仅在

doesComplain
上出现以下错误。

Type '({ a: number; b?: undefined; } | { b: number; a?: undefined; })[]' is not assignable to type 'myType[]'.
  Type '{ a: number; b?: undefined; } | { b: number; a?: undefined; }' is not assignable to type 'myType'.
    Type '{ a: number; b?: undefined; }' is not assignable to type 'myType'.
      Property 'b' is incompatible with index signature.
        Type 'undefined' is not assignable to type 'number'.

我尝试过的:

虽然不完全相同的问题,但我见过一些类似的问题,但在我看来,没有一个解决方案有效。

此处显示的解决方案,例如,需要数组具有固定数量的值,因此它不适合我的情况。

与此类似的一些解决方案,例如,建议使用

myType
定义
number | undefined
,我认为我不想这样做,因为我不希望任何键具有未定义的值。如果对象上存在键,则其值将被定义。

到目前为止,消除错误的唯一方法是在

// @ts-ignore
上方添加
doesComplain
,但这有点违背了使用 Typescript 的目的。

typescript
1个回答
0
投票

我也遇到过类似的问题,并且脱发试图了解发生了什么。

首先,让我们看看您的

.map()
结果无需输入变量。

const untypedMappedResult = [1, 0, 0, 0, 1, 0].map((e) => {
  return (e === 1) ? { a: 1 } : { b: 2 };
});

/*
const untypedMappedResult: ({
    a: number;
    b?: undefined;
} | {
    b: number;
    a?: undefined;
})[]
*/

如您所见,结果并不是您所期望的。 联合中的两个对象都有两个属性。

要解决此问题,您应该只提供类型断言...

const typedMappedResult = [1, 0, 0, 0, 1, 0].map((e) => {
  return ((e === 1) ? { a: 1 } : { b: 2 }) as myType;
});

/*
const typedMappedResult: myType[]
*/

请注意,我不需要输入变量;由此推断。

游乐场示例

© www.soinside.com 2019 - 2024. All rights reserved.