TypeScript参数定义覆盖

时间:2020-01-10 22:40:05

标签: javascript reactjs typescript

我正在使用@types/react-simple-maps,并且使用的是其中一种类型定义:

interface GeographiesChildrenArgument {
    geographies: object[];
    path: GeoPath;
    projection: GeoProjection;
}

他们使用object[]

现在,当我尝试使用这些定义时,我必须执行以下操作:

{({ geographies }): React.ReactNodeArray => geographies.map(
  (geo: object) => (
    ...

有没有一种方法可以使对象更具体?如果我尝试:

{({ geographies }: { geographies: GeographyType[] }): React.ReactNodeArray => geographies.map(
  (geo: GeographyType) => (
    ...

但随后出现以下错误:

Type '({ geographies }: { geographies: GeographyType[]; }) => React.ReactNodeArray' is not assignable to type '((data: GeographiesChildrenArgument) => void) | (((data: GeographiesChildrenArgument) => void) & string) | (((data: GeographiesChildrenArgument) => void) & number) | ... 5 more ... | undefined'.
Type '({ geographies }: { geographies: GeographyType[]; }) => React.ReactNodeArray' is not assignable to type '(data: GeographiesChildrenArgument) => void'.
Types of parameters '__0' and 'data' are incompatible.
Type 'GeographiesChildrenArgument' is not assignable to type '{ geographies: GeographyType[]; }'.
Types of property 'geographies' are incompatible.
Type 'object[]' is not assignable to type 'GeographyType[]'.
Type '{}' is missing the following properties from type 'GeographyType': type, geometry, propertiests (2322)
index.d.ts(95, 5): The expected type comes from property 'children' which is declared here on type 'IntrinsicAttributes & GeographiesProps & { children?: ReactNode; }'

因此,有没有办法将object[]覆盖为我的对象定义:GeographyType[]

2 个答案:

答案 0 :(得分:1)

我会尝试扩展接口。您无法更改现有属性的类型。 下面是这样的。让我知道是否有效。 还要检查一下这与修改现有类型Overriding interface property type defined in Typescript d.ts file

有关
 {({ geographies }: { geographies: object[] extends GeographyType[] }): React.ReactNodeArray => 
  geographies.map(
   (geo: GeographyType) => (
  ...

答案 1 :(得分:0)

这是一个愚蠢的答案,但是最终的解决方案是我只是按照他们的指南中的建议使用@types/react-simple-maps,将object更改为any any上的限制,因为object的限制太多。