设置接口方法时,VSCode 出现智能感知错误
Getting intellisense error in VSCode, when setting a method of an Interface
在下面的代码中,智能感知工作正常
test.d.ts
:
export interface ITest {
foo: string;
setFoo(foo: string): ITest;
}
export as namespace JSDoc;
test.js
:
/** @typeof {import("./test")} JSDoc */
/**
* @returns {JSDoc.ITest}
*/
function test() {
return {
foo: "",
setFoo: function (foo) {
this.foo = foo;
return this;
}
};
}
exports.test = test;
但是如果我取消注释 //this.foo = this.foo;
行,我会在 test
函数的返回对象上收到以下警告:
Type 'typeof setFoo' is not assignable to type '(foo: string) =>
ITest'. Property 'setFoo' is missing in type 'setFoo' but required
in type 'ITest'.ts(2322) test.d.ts(3, 5): 'setFoo' is declared here.
test.d.ts(3, 5): The expected type comes from property 'setFoo' which
is declared here on type 'ITest'
这里也是图片形式:
知道为什么会发生这种情况,我该如何解决?
您在 test.d.js
中声明了 bar
,它是 typeof ITest
,但是在您的 bar
函数中您没有。
尝试这样的事情并检查:
function bar() {
this.foo = this.foo;
this.bar = this;
return this;
}
在下面的代码中,智能感知工作正常
test.d.ts
:
export interface ITest {
foo: string;
setFoo(foo: string): ITest;
}
export as namespace JSDoc;
test.js
:
/** @typeof {import("./test")} JSDoc */
/**
* @returns {JSDoc.ITest}
*/
function test() {
return {
foo: "",
setFoo: function (foo) {
this.foo = foo;
return this;
}
};
}
exports.test = test;
但是如果我取消注释 //this.foo = this.foo;
行,我会在 test
函数的返回对象上收到以下警告:
Type 'typeof setFoo' is not assignable to type '(foo: string) => ITest'. Property 'setFoo' is missing in type 'setFoo' but required in type 'ITest'.ts(2322) test.d.ts(3, 5): 'setFoo' is declared here. test.d.ts(3, 5): The expected type comes from property 'setFoo' which is declared here on type 'ITest'
这里也是图片形式:
知道为什么会发生这种情况,我该如何解决?
您在 test.d.js
中声明了 bar
,它是 typeof ITest
,但是在您的 bar
函数中您没有。
尝试这样的事情并检查:
function bar() {
this.foo = this.foo;
this.bar = this;
return this;
}