我需要一种通过课堂访问obj的方法. 为此,我想使用泛型类型.
问题是,在类中,我得到了一个错误—它是不可能判断这个. locators是否包含输入字段.
type '{ form1: { item2: { checkbox: string; input: string; }; }; form2: { item1: { checkbox: string; }; }; }[T][F]' is not assignable to type 'object'.
Type '{ form1: { item2: { checkbox: string; input: string; }; }; form2: { item1: { checkbox: string; }; }; }[T][keyof { form1: { item2: { checkbox: string; input: string; }; }; form2: { item1: { checkbox: string; }; }; }[T]]' is not assignable to type 'object'.
Type '{ form1: { item2: { checkbox: string; input: string; }; }; form2: { item1: { checkbox: string; }; }; }[T][string] | { form1: { item2: { checkbox: string; input: string; }; }; form2: { item1: { checkbox: string; }; }; }[T][number] | { ...; }[T][symbol]' is not assignable to type 'object'.
Type '{ form1: { item2: { checkbox: string; input: string; }; }; form2: { item1: { checkbox: string; }; }; }[T][string]' is not assignable to type 'object'
如何解决?我想提一下,类型必须从const obj
中推断,我不想定义任何接口/类型.
const obj = {
form1: {
item2: {
checkbox: 'checkbox',
input: 'input',
}
},
form2: {
item1: {
checkbox: 'busin'
}
}
};
type ObjType = typeof obj;
type ProgramKeys = keyof ObjType;
type FormKeys<T extends ProgramKeys> = keyof ObjType[T];
class CheckboxFormOne<T extends ProgramKeys, F extends FormKeys<T>> {
locators: ObjType[T][F];
constructor(public program: T, public form: F) {
this.locators = obj[program][form];
}
fillInput(input: keyof typeof obj[T][F]) {
if ('input' in this.locators && typeof this.locators[input] === 'string') {
this.locators.input
}
}
}
new CheckboxFormOne('form1', 'item2').fillInput('input')