typescript - 属性 X 的类型不兼容

标签 typescript interface

我刚刚开始使用 Typescript,但遇到了一个奇怪的问题。

我已经声明了一个这样的接口(interface):

Location.d.ts

interface Location {
    lat: number;
    lng: number;
}

这个接口(interface)的使用方式如下:

reducer.tsx

interface MapState extends State {
    locations: Location[];
}

现在,我尝试声明一个 MapState 类型的变量,但收到错误:

Type ... is not assignable to type 'MapState'. Types of property 'locations' are incompatible. Type ... is not assignable to type 'Location[]'. Type ... is not assignable to type 'Location'. Property 'hash' is missing in type ...

这是我的声明:

const initialState: MapState = {
    locations: [
        { lat: 33.488069, lng: -112.072972 }
    ]
};

如果我显式转换位置,那么它就可以工作:

const initialState: MapState = {
    locations: [
        ({ lat: 33.488069, lng: -112.072972 } as Location)
    ]
};

但这实在是太冗长了。我在这里遗漏了什么吗?

最佳答案

Property 'hash' is missing in type

这意味着发生错误的位置的 Location 不是您的 Location 类型 - 它是 dom.d.ts 中定义的浏览器位置对象的类型。

您可能没有在该文件 (reducer.tsx) 中导入您的 Location 类型,或者有其他原因导致编译器看不到它。

关于typescript - 属性 X 的类型不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51315454/

相关文章:

typescript - ionic 2 供应商

javascript - 在javascript中检查给定字符串数组中的字符串匹配

Java接口(interface): compiler error

c# - 将派生类转换为 C# 中的另一个派生类

.net - 为什么.NET框架中没有 "set"接口(interface)?

angular - 路由器事件问题

function - 在 Typescript 中,如何在不将它们放入模块的情况下使用另一个 TS 文件中定义的函数?

html - 仅显示单击元素 Angular 2 的类

android - 将数据从 DialogFragment 返回到适配器

java - 通过android中的接口(interface)将gcm注册ID从GCMBaseIntentService类传递到MainActivity