解决 cannot redeclare block-scoped variable 问题

cannot redeclare block-scoped variable

依照5分钟上手TypeScript,全局安装typescript,新建.ts文件main.ts,编译main.ts,得到main.js。

//main.ts
type IdDisplay = {
    id:string,
    display:string
}

const list:IdDisplay[] = [
    {
        id:"foo",
        display:"共和国勋章"
    },
    {
        id:"bar",
        display:"七一勋章"
    }
];

const fooIndex = list.map(item => item.id).indexOf("foo");
console.log(fooIndex);
//main.js
var list = [
    {
        id: "foo",
        display: "共和国勋章"
    },
    {
        id: "bar",
        display: "七一勋章"
    }
];
var fooIndex = list.map(function (item) { return item.id; }).indexOf("foo");
console.log(fooIndex);

我这边使用的是编辑器是vscode,编译完后,编译器报错:Cannot redeclare block-scoped variable ‘list’
在这里插入图片描述
其实,main.ts中的代码并没有问题,只不过ts中声明的变量、函数等被放在全局作用域中,而在编译生成的main.js里,也有同样的一份变量名、函数,所以vscode会报错提示说"redeclare"。
针对上述问题,可以在main.ts中添加export {},让typescript认为main.ts是一个模块,这样就避免报错了。

//main.ts
export {};
type IdDisplay = {
    id:string,
    display:string
}

const list:IdDisplay[] = [
    {
        id:"foo",
        display:"共和国勋章"
    },
    {
        id:"bar",
        display:"七一勋章"
    }
];

const fooIndex = list.map(item => item.id).indexOf("foo");
console.log(fooIndex);

编译main.ts,得到main.js 。

"use strict";
exports.__esModule = true;
var list = [
    {
        id: "foo",
        display: "共和国勋章"
    },
    {
        id: "bar",
        display: "七一勋章"
    }
];
var fooIndex = list.map(function (item) { return item.id; }).indexOf("foo");
console.log(fooIndex);
参考文章

5分钟上手typescript
解决typescript Cannot redeclare block-scoped variable

  • 12
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值