簡體   English   中英

后續變量聲明必須有相同的類型錯誤 lodash require TypeScript

[英]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 項目中, importrequire()更受歡迎,原因如下,以及您需要使用import從其他文件導入任何類型的事實。

因此,我建議將您的require()更改為import語句,這應該會給您帶來更少的麻煩。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM