需要帮助从反应小册子中为打字稿定义正确的类型
问题描述:
我有一个'第一个'项目尝试使用react-scripts-ts和反应小册子。需要帮助从反应小册子中为打字稿定义正确的类型
我试图创建下面的类,它看起来像TI应该是直截了当:
import {map, TileLayer, Popup, Marker } from 'react-leaflet';
class LeafletMap extends React.Component {
constructor() {
super();
this.state = {
lat: 51.505,
lng: -.09,
zoom: 13
};
}
render() {
const position = [ this.state.lat, this.state.lng];
return (
<Map center={position} zoom={this.state.zoom}>
<TileLayer
url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"
attribution="© <a href='http://osm.org/copyright'>OpenStreetMap</a> contributors"
/>
<Marker position={position}>
<Popup>
<span>A pretty CSS3 popup.<br/>Easily customizable.</span>
</Popup>
</Marker>
</Map>
);
}
}
我正达的错误
住宅“纬度”不上类型存在'只读< {}>'
上的纬度和经度分配到位置(TS2339),同样
类型'any []'不可分配给类型'[number,number] | LatLng | LatLngLiteral |未定义”。
将位置分配给中心(TS2322)。
从我可以告诉这是/连接到打字稿版本,但我相信我有一个新的版本,这不应该是这样的。
的package.json:
{
"name": "map-experiment",
"version": "0.1.0",
"private": true,
"dependencies": {
"@types/geojson": "^1.0.4",
"@types/leaflet": "^1.2.0",
"@types/react-leaflet": "^1.1.4",
"leaflet": "^1.2.0",
"prop-types": "^15.6.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-leaflet": "^1.7.0",
"react-scripts-ts": "2.7.0"
},
"scripts": {
"start": "react-scripts-ts start",
"build": "react-scripts-ts build",
"test": "react-scripts-ts test --env=jsdom",
"eject": "react-scripts-ts eject"
},
"devDependencies": {
"@types/jest": "^21.1.2",
"@types/node": "^8.0.33",
"@types/react": "^16.0.10",
"@types/react-dom": "^16.0.1"
}
}
我试过中堂定义位置[Number, Number]
,我应该给它一个不同类型的注释?概念没有打字稿
证明可以发现here
答
你没有指定你的状态的类型。试试这个:
class LeafletMap extends React.Component<{}, {lat: number, lng: number, zoom: number}> {
即使在这之后,还有一个额外的复杂因素。通过打字稿用于位置推断类型 :
const position = [ this.state.lat, this.state.lng ];
...是number[]
(编号中的任何阵列),其是不同的类型[number, number]
(正好用两个数字的阵列)。您可以通过给定类型解决这个问题:
const position: [number, number] = [ this.state.lat, this.state.lng ];
或者使用单张接受其它形式:
const position = {lat: this.state.lat, lng: this.state.lng };
答
你应该总是调用super
方法与道具作为属性的构造函数。 查看我的代码更改。
class LeafletMap extends React.Component {
constructor(props) {
super(props);
this.state = {
lat: 51.505,
lng: -.09,
zoom: 13
};
}
...
}
谢谢你的注意!不幸的是,这似乎没有效果。 – Kludge