我刚刚开始使用 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/