无法重新声明块作用域变量(打字稿) [英] cannot redeclare block scoped variable (typescript)

查看:365
本文介绍了无法重新声明块作用域变量(打字稿)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个节点应用程序,并在.js文件中的每个文件中用来执行此操作,以在各种程序包中进行该操作.

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

let co = require("co");

但是得到

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

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 let was scoped to the current file.

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

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

有人可以解释吗?

推荐答案

关于错误本身,let用于声明local 变量. basarat.gitbooks.io/typescript/content/docs/let.html"rel =" noreferrer>块作用域,而不是函数作用域.它也比var更严格,因此您不能执行以下操作:

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

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

还请注意,switch块内的case子句不会创建自己的块作用域,因此,如果不使用{}来分别创建一个块,则无法跨多个case重新声明相同的局部变量

Also note that case clauses inside switch blocks 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.

对于导入,您可能会遇到此错误,因为TypeScript不能将文件识别为实际模块,并且看来模型级定义最终是该文件的全局定义.

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.

尝试以标准 ES6 方式导入外部模块,该方式不包含任何显式分配,并应使TypeScript正确将您的文件识别为模块:

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

import * as co from "./co"

如果您已经按预期拥有名为co的内容,这仍将导致编译错误.例如,这将是一个错误:

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

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


如果遇到错误找不到模块co" ...


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

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

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 declare your module in a .d.ts definition file that doesn't contain module-level exports:

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

这篇关于无法重新声明块作用域变量(打字稿)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆