对象类型不继承所有原生 obj 方法

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

我为自定义对象形状创建一个类型,如下所示:

type A = {
  readonly prop1: string;
  readonly prop2: string;
}

然后在一种方法中我像这样使用它:

const getStuff = (obj: A) =>
   obj.reduce((acc, curr) => {
     ...
   })
}

这是在抱怨

property 'reduce' does not exist on type A
。我假设
A
作为对象类型会继承 JS 对象的所有本机方法,但我猜不是。

我怎样才能告诉它这样做?

typescript
1个回答
1
投票

因为原生 javascript 对象没有

reduce
方法。尝试
obj.toString()
obj.hasOwnProperty()
。也许您想
Array.reduce
?如果是这样,请这样做:

type A<T>  =  {
    readonly prop1: string;
    readonly prop2: string;
} & Array<T>;
© www.soinside.com 2019 - 2024. All rights reserved.