下面是我想要做的一些代码:
- 具有几个成员字段和函数的类;
- 这个类提供一个名为
callMe
的函数; -
callMe
的参数将被限制为此类的成员名称之一; - 只接受成员字段的名称,应排除成员函数的名称.
奇怪的是:
- 如果我用一个实例调用
callMe
函数,一切都会像预期的那样顺利. - 但是,如果我在这个类的成员函数中调用
callMe
,就会出现错误.
详情如下:
// I'd like to use this `Filter` to get all the non-function field names of a type
type Filter<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T] & string;
class BaseClass {
// This function should only accept a parameter which only matches the non-function member names
public callMe<V extends Filter<this>>(param: V) {}
}
class MyClass extends BaseClass {
// These member field should be involved
public stringField: string = '';
public numberField: number = 0;
public booleanField: boolean = false;
// These member functions should be excluded
public shouldBeExclude() {}
public test() {
// this line is error:
// TS2345: Argument of type string is not assignable to parameter of type Filter<this>
// Type 'string' is not assignable to type 'this[keyof this] extends Function ? never : keyof this'
this.callMe('stringField');
}
}
const instance = new MyClass();
// However these lines work as expected
instance.callMe('stringField'); // Valid
instance.callMe('numberField'); // Valid
instance.callMe('shouldBeExclude'); // Invalid: TS2345: Argument of type 'shouldBeExclude' is not assignable to parameter of type Filter<MyClass>
我怎样才能使Filter
与成员函数test
一起工作?