Typescript未检测到非法参数
Typescript在下面的代码中没有检测到任何错误Typescript未检测到非法参数,typescript,Typescript,Typescript在下面的代码中没有检测到任何错误 interface testIF { test(): void; test2(map: Map<string, number>): void } function f(): testIF { return { test: function () { let map: Map<string, string> = new Map();
interface testIF {
test(): void;
test2(map: Map<string, number>): void
}
function f(): testIF {
return {
test: function () {
let map: Map<string, string> = new Map();
this.test2(map); // Passing Map<string, string>
},
test2: function(map: Map<string, number>) {
}
}
}
调用该方法的方式可以更改
this
的值,因此TypeScript会在默认情况下将this
设置为any
类型,从而关闭类型检查。通过创建一个名为的伪参数this
参数,可以告诉TypeScript上下文:
function f(): testIF {
return {
test: function (this: testIF /* fake "this" parameter */) {
let map: Map<string, string> = new Map();
this.test2(map); // Error
},
test2: function(map: Map<string, number>) {
}
}
}
函数f():testIF{
返回{
测试:函数(this:testIF/*伪“this”参数*/){
让map:map=newmap();
this.test2(map);//错误
},
test2:函数(map:map){
}
}
}
作为@PSL建议,我已在
tsconfig.json
上将noImplicitThis
设置为true
。现在,Typescript可以检测到错误。尝试打开tsconfig中的noImplicitThis
编译器选项。我相信如果没有这个(无法解释为什么-可能是一个bug)这个
在使用工厂函数syntax时被隐式键入为any
,谢谢评论。将noImplicitThis
设置为true
可以检测错误。你能回答一下吗?我会接受的。如果你设置了这个标志,这个的类型会改变吗?(即使正确使用了该方法,您是否仍会收到错误?)设置noImplicitThis
后,上述代码生成错误TS2345:Map类型的参数不可分配给Map类型的参数。类型“string”不能分配给类型“number”。
。它看起来是的类型,这个
是testIF
。太酷了!我不知道noimplicitt这个
会导致编译器将这个
解释为对象的类型。我认为如果这个
被解释为任何
,这只会导致编译器出错。
function f(): testIF {
return {
test: function (this: testIF /* fake "this" parameter */) {
let map: Map<string, string> = new Map();
this.test2(map); // Error
},
test2: function(map: Map<string, number>) {
}
}
}