我将其分解为MapComponent和GeoPoint类这两个项目。我在这里想念什么?
MapComponent
// Initiate
const response: Array<LatLngExpression> = []; // Seems to work
const response: [LatLngExpression] = []; // Msg: Type any[] is not assignable to type [any]
// Add a value to the array
response.push(geoPoint.getLatLng());
GeoPoint
export clas GeoPoint {
private _id: string;
private _value: LatLngExpression; // This is a leaflet.LatLngExpression
private _selected: boolean = false;
constructor (id: string, latLng:LatLngExpression, selected?:boolean) {
this._id = id;
this._value = latLng;
if(selected){
this._selected = selected;
}
}
set()... // you get the idea
get()... // you get the idea
}
您的“似乎可以工作”是正确的:
const response: Array<LatLngExpression> = [];
您也可以这样写:
const response: LatLngExpression[] = [];
LatLngExpression[]
是的类型response
。
《手册》的“ 基本类型”>“数组”部分对此进行了介绍。
在许多情况下,您也可以完全不使用类型,并允许TypeScript进行推断。但是,如果您从一个空数组开始,那实际上比提供类型注释要尴尬得多,因为您必须提供一个类型断言。因此,它可能不是您想要的,而仅仅是为了完整性:
// I probably wouldn't do it this way
const response = [] as LatLngExpression[];
@Elijah-我不知道TypeScript团队是否有偏好。除非您要从它们
LatLngExpression[]
首先显示样式的事实中推断出一个,否则链接的文档中没有任何内容。就个人而言,我更喜欢LatLngExpression[]
的风格并非最不重要的,因为它是类似于其他语言(Java,C#),但我不是一个打字稿大师(在所有)。:-)