Javascript Typescript-Can';t访问“;这";有点

Javascript Typescript-Can';t访问“;这";有点,javascript,arrays,typescript,Javascript,Arrays,Typescript,我正在使用打字脚本。我使用方法数组。一些在类中的方法内部。 像这样: class Example { constructor(private readonly foo: string) {} test(array: Array<string>) { array.some(function (element) { if (element == this.foo) { return true

我正在使用打字脚本。我使用方法
数组。一些
在类中的方法内部。
像这样:

class Example {
    constructor(private readonly foo: string) {}

    test(array: Array<string>) {
        array.some(function (element) {
            if (element == this.foo) {
                return true 
            } else {
                return false 
            }
        })

    }
}
改用a来保留
引用

class Example {
    constructor(private readonly foo: string) {}

    test(array: Array<string>) {
        array.some(element => {
            if (element == this.foo) {
                return true 
            } else {
                return false 
            }
        })

    }
}
类示例{
构造函数(私有只读foo:string){}
测试(数组:数组){
array.some(元素=>{
if(element==this.foo){
返回真值
}否则{
返回错误
}
})
}
}

您可以在
数组中传递
this
。一些
方法使用它作为第二个参数(因此在回调之后)。例如,
array.some(函数(元素){…},this)
可以工作。但是有很多其他的方法可以避免这个问题,我试过这个方法,但是我有很多错误,我会把它们放在我父母的帖子里。是的,我明白了。这里有一些混淆,因为您不需要向
添加类型注释(您也不能以显示的方式添加)。您只需要将其作为参数像任何其他参数一样传递给
some
方法,因此删除
:Example
部分,使其读起来与
.some(function(element){…},this)
一样。当我删除类型注释时,我在引用
this.foo
时遇到以下错误。“这隐式地有类型any,因为它没有类型注释”啊,在这种情况下,你可能确实需要给它一个类型。在这种情况下,正确的语法应该是
.some(函数(元素){…},例如)
语法只能在声明变量、函数参数或类字段时使用。在typescript中使用
as
关键字来进行类型断言,这正是您在这里需要的。
class Example {
    constructor(private readonly foo: string) {}

    test(array: Array<string>) {
        array.some(element => {
            if (element == this.foo) {
                return true 
            } else {
                return false 
            }
        })

    }
}