[英]Subsequent variable declarations must have the same type error for lodash require TypeScript
我不明白為什么 TS 不喜歡歷史或 lodash 要求:
對於_ = require('lodash'),
我得到 TS 錯誤Subsequent variable declarations must have the same type. Variable '_' must be of type 'LoDashStatic', but here has type 'any'
Subsequent variable declarations must have the same type. Variable '_' must be of type 'LoDashStatic', but here has type 'any'
對於require('connect-history-api-fallback')
我得到 TS 錯誤Cannot redeclare block-scoped variable 'history'
@types/lodash
和@types/connect-history-api-fallback
已經安裝。
api.ts
const _ = require('lodash'),
countryTable = require('./shared/data/countries.json'),
compression = require('compression'),
express = require('express'),
{ on, use } = (module.exports = express()),
history = require('connect-history-api-fallback'),
oneYear = 31536000;
use(compression());
module.exports = on('error', function (err: string) {
console.log(err);
})
.get('/api/v1/countries', (res: any) => {
res.json(
countryTable.map((country: any) => {
return _.pick(country, ['id', 'name', 'images']);
})
);
})
.use(history())
.use(
express.static('dist', {
maxage: oneYear,
})
)
.use((res: any) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,OPTIONS');
res.header(
'Access-Control-Allow-Headers',
'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json'
);
res.send('Sorry, Page Not Found');
});
Typescript 不喜歡您的const history
與瀏覽器提供的全局window.history
中的 window.history 沖突。
如果您只是將名稱更改為historyApi
,它應該可以按您的預期工作:
historyApi = require('connect-history-api-fallback'),
或者您可以import
關鍵字,這似乎不介意覆蓋全局變量。
import history from 'connect-history-api-fallback'
在大多數 typescript 項目中, import
比require()
更受歡迎,原因如下,以及您需要使用import
從其他文件導入任何類型的事實。
因此,我建議將您的require()
更改為import
語句,這應該會給您帶來更少的麻煩。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.