在导出的函数中访问“this” - TypeScript

accessing 'this' in exported function - typescript

提问人:ddor254 提问时间:1/3/2022 更新时间:1/3/2022 访问量:296

问:

我正在尝试理解尝试在导出函数中访问/传递“this”时遇到的以下错误,我有以下代码:

export async function main() {
try {
    console.log(this)
catch (e: any) {

}

尝试编译时给我这个错误:

src/main.ts:55:32 - error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

55      console.log( this);
                                  ~~~~

src/main.ts:28:23
    28 export async function main() {
                             ~~~~
    An outer value of 'this' is shadowed by this container.

我不明白为什么我在访问它时遇到问题 - “this”应该是功能范围吗?还是全局对象?谁在隐藏这个变量,我该如何解决这个问题?

node.js 打字稿

评论

0赞 bas 1/3/2022
这回答了你的问题吗?打字稿错误:此容器隐藏了“this”的外部值
1赞 slebetman 1/3/2022
这取决于你如何称呼它。上面的代码没有确定什么是。这就是你得到错误的原因:取决于你如何称呼它可能是不同的事情。thisthis
0赞 ddor254 1/3/2022
我只需运行“main()”即可从另一个文件调用(因为它是一个导出的函数)(async () => { main()})();
1赞 CherryDT 1/3/2022
在这种情况下,将是(在严格模式下)或全局对象。如果使用 both 也不作为对象属性调用函数,则使用 .thisundefinedmain.call(someThisValue)const obj = { main }; obj.main()this

答:

1赞 HTN 1/3/2022 #1

错误来自编译选项。 您可以删除此选项(不推荐)或声明以下类型的类型:noImplicitThisthis

export async function main(this: unknown) {
    try {
        console.log(this);
    } catch (e: any) {

    }
}

游乐场链接: https://tsplay.dev/mLLpbm

评论

0赞 ddor254 1/3/2022
但是错误的根源是什么?我的意思是用 unknown 传递它,只需声明作为函数的参数。为什么我不能在不声明的情况下访问它?thisthis
1赞 CherryDT 1/3/2022
因为没有定义否则应该是什么类型......如果你写,将是 ,如果你写,那么将是 ,如果你处于严格模式,只是写,那么将是 ,等等。thismain.call(123)thisnew Number(123)const obj = { main }; obj.main()thisobjmain()thisundefined