typescript 不能重新声明块作用域变量(打字稿)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35758584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:58:17  来源:igfitidea点击:

cannot redeclare block scoped variable (typescript)

typescriptrequire

提问by dcsan

I'm building a node app, and inside each file in .js used to doing this to require in various packages.

我正在构建一个节点应用程序,并且在 .js 中的每个文件中都习惯于在各种包中执行此操作。

let co = require("co");

But getting

但是得到

enter image description here

在此处输入图片说明

etc. So using typescript it seems there can only be one such declaration/require across the whole project? I'm confused about this as I thought letwas scoped to the current file.

等等。所以使用打字稿似乎在整个项目中只能有一个这样的声明/要求?我对此感到困惑,因为我认为let范围仅限于当前文件。

I just had a project that was working but after a refactor am now getting these errors all over the place.

我刚刚有一个正在运行的项目,但经过重构后,我现在到处都是这些错误。

Can someone explain?

有人可以解释一下吗?

采纳答案by John Weisz

Regarding the error itself, letis used to declare localvariables that exist in block scopesinstead of function scopes. It's also more strict than var, so you can't do stuff like this:

关于错误本身,let用于声明存在于块作用域而不是函数作用域中的局部变量。它也比 更严格,所以你不能做这样的事情:var

if (condition) {
    let a = 1;
    ...
    let a = 2;
}

Also note that caseclauses inside switchblocks don't create their own block scopes, so you can't redeclare the same local variable across multiple cases without using {}to create a block each.

另请注意,块case内的子句switch不会创建自己的块作用域,因此您不能在case不使用{}每个创建块的情况下跨多个s重新声明相同的局部变量。



As for the import, you are probably getting this error because TypeScript doesn't recognize your files as actual modules, and seemingly model-level definitions end up being global definitions for it.

至于导入,您可能会收到此错误,因为 TypeScript 不会将您的文件识别为实际模块,并且看似模型级别的定义最终成为它的全局定义。

Try importing an external module the standard ES6way, which contains no explicit assignment, and should make TypeScript recognize your files correctly as modules:

尝试以标准ES6方式导入外部模块,其中不包含显式赋值,并且应该使 TypeScript 将您的文件正确识别为模块:

import * as co from "./co"

This will still result in a compile error if you have something named coalready, as expected. For example, this is going to be an error:

如果您co已经按预期命名了某些内容,这仍然会导致编译错误。例如,这将是一个错误:

import * as co from "./co"; // Error: import definition conflicts with local definition
let co = 1;


If you are getting an error "cannot find module co"...

如果您收到错误“找不到模块 co”...

TypeScript is running full type-checking against modules, so if you don't have TS definitions for the module you are trying to import (e.g. because it's a JS module without definition files), you can declareyour module in a .d.tsdefinition file that doesn't contain module-level exports:

TypeScript 正在对模块运行完整的类型检查,因此如果您尝试导入的模块没有 TS 定义(例如,因为它是一个没有定义文件的 JS 模块),您可以在定义文件中声明您的模块.d.ts'不包含模块级导出:

declare module "co" {
    declare var co: any;
    export = co;
}

回答by Neville Omangi

The best explanation I could get is from Tamas Piro's post.

我能得到的最好解释来自Tamas Piro 的帖子

TLDR; TypeScript uses the DOM typings for the global execution environment. In your case there is a 'co' property on the global window object.

TLDR;TypeScript 将 DOM 类型用于全局执行环境。在您的情况下,全局窗口对象上有一个 'co' 属性。

To solve this:

要解决这个问题:

  1. Rename the variable, or
  2. Use TypeScript modules, and add an empty export{}:
  1. 重命名变量,或
  2. 使用 TypeScript 模块,并添加一个空导出{}:
export{};

or

  1. Configure your compiler options by not adding DOM typings:

或者

  1. 通过不添加 DOM 类型来配置您的编译器选项:

Edit tsconfig.json in the TypeScript project directory.

编辑 TypeScript 项目目录中的 tsconfig.json。

{
    "compilerOptions": {
        "lib": ["es6"]
      }
}

回答by Tom Mettam

I was receiving this similar error when compiling my Node.JS Typescript application:

在编译我的 Node.JS Typescript 应用程序时,我收到了这个类似的错误:

node_modules/@types/node/index.d.ts:83:15 - error TS2451: Cannot redeclare block-scoped variable 'custom'.

node_modules/@types/node/index.d.ts:83:15 - error TS2451: Cannot redeclare block-scoped variable 'custom'.

The fix was to removethis:

修复是删除这个:

"files": [
  "./node_modules/@types/node/index.d.ts"
]

and to replace it with this:

并用这个替换它:

"compilerOptions": {
  "types": ["node"]
}

回答by Belter

Use IIFE(Immediately Invoked Function Expression), IIFE

使用IIFE(Immediately Invoked Function Expression)IIFE

(function () {
    all your code is here...

 })();

回答by django dev

I got the same problem, and my solution looks like this:

我遇到了同样的问题,我的解决方案如下所示:

// *./module1/module1.ts*
export module Module1 {
    export class Module1{
        greating(){ return 'hey from Module1'}
    }
}


// *./module2/module2.ts*
import {Module1} from './../module1/module1';

export module Module2{
    export class Module2{
        greating(){
            let m1 = new Module1.Module1()
            return 'hey from Module2 + and from loaded Model1: '+ m1.greating();
        }
    }
}

Now we can use it on the server side:

现在我们可以在服务器端使用它:

// *./server.ts*
/// <reference path="./typings/node/node.d.ts"/>
import {Module2} from './module2/module2';

export module Server {
    export class Server{
        greating(){
            let m2 = new Module2.Module2();
            return "hello from server & loaded modules: " + m2.greating();
        }
    }
}

exports.Server = Server;

// ./app.js
var Server = require('./server').Server.Server;
var server = new Server();
console.log(server.greating());

And on the client side too:

在客户端也是:

// *./public/javscripts/index/index.ts*

import {Module2} from './../../../module2/module2';

document.body.onload = function(){
    let m2 = new Module2.Module2();
    alert(m2.greating());
}

// ./views/index.jade
extends layout

block content
  h1= title
  p Welcome to #{title}
  script(src='main.js')
  //
    the main.js-file created by gulp-task 'browserify' below in the gulpfile.js

And, of course, a gulp-file for all of this:

当然,还有一个用于所有这些的 gulp 文件:

// *./gulpfile.js*
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    runSequence = require('run-sequence'),
    browserify = require('gulp-browserify'),
    rename = require('gulp-rename');

gulp.task('default', function(callback) {

    gulp.task('ts1', function() {
        return gulp.src(['./module1/module1.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module1'))
    });

    gulp.task('ts2', function() {
        return gulp.src(['./module2/module2.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./module2'))
    });

    gulp.task('ts3', function() {
        return gulp.src(['./public/javascripts/index/index.ts'])
            .pipe(ts())
            .pipe(gulp.dest('./public/javascripts/index'))
    });

    gulp.task('browserify', function() {
        return gulp.src('./public/javascripts/index/index.js', { read: false })
            .pipe(browserify({
                insertGlobals: true
            }))
            .pipe(rename('main.js'))
            .pipe(gulp.dest('./public/javascripts/'))
    });

    runSequence('ts1', 'ts2', 'ts3', 'browserify', callback);
})

Updated.Of course, it's not neccessary to compile typescript files separatly. runSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback)works perfect.

更新。当然,没有必要单独编译打字稿文件。 runSequence(['ts1', 'ts2', 'ts3'], 'browserify', callback)工作完美。

回答by danday74

I got this error when upgrading

升级时出现此错误

gulp-typescript 3.0.2 → 3.1.0

吞咽打字稿 3.0.2 → 3.1.0

Putting it back to 3.0.2 fixed it

把它放回 3.0.2 修复它