我有一个包含一堆方法的接口:
@Injectable()
export class SharedService {
serverURL: string;
expertMetadataSetSubject = new Subject<any>();
metadataEmptySubject = new Subject<void>();
singleSubject = new Subject<void>();
constructor(private http: HttpClient, private envService: EnvService) {
this.serverURL = envService.serverURL;
}
search(): Observable<String[]> {
return this.http.get<String[]>(this.serverURL + 'v2/meta/profile', {});
}
onMetadataEmpty() {
this.metadataEmptySubject.next();
}
onSingleInputChange(): void {
this.singleSubject.next();
}
等。
此服务注入到一个组件中,该组件将函数名称作为@Input()
获取,该组件包含此服务中的函数名称作为字符串。 我想动态调用适当的方法。
@Component({
selector: 'app-registration',
templateUrl: './registration.html',
styleUrls: ['./registration.css'],
})
export class RegistrationComponent implements OnInit {
@Input() name: string;
@Input() title: string;
@Input() onChange: string;
@Input() control!: FormControl;
constructor(private readonly sharedService: SharedService) {}
onClick(event: any) {
const value = event.target.innerHTML.trim();
this.control.setValue(value);
if (this.onChange) {
this.sharedService[this.onChange](value);
}
}
}
.html:
<app-registration [control]="getControlByIndex('employee')" onChange="onSingleInputChange" title="namespace"></app-registration>
我得到了标题中提到的错误:
error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'SharedService'.
我想避免添加此参数:"suppressImplicitAnyIndexErrors": true
知道吗?
谢谢
您收到此错误是因为this.onChange
可以是任何字符串,但不一定引用对象SharedService
属性。
使用keyof应该可以解决问题
this.sharedService[this.onChange as keyof SharedService](value);
或者你甚至可以这样做
@Input() onChange: keyof SharedService;
现在,由于keyof引用对象的属性和方法,最好的方法是创建一个类型或仅包含方法的接口
// onChange: keyof ISharedService;
interface ISharedService {
onMetadataEmpty(): void;
onSingleInputChange(): void;
}
// onChange: SharedServiceMethodType;
type SharedServiceMethodType = 'onMetadataEmpty' | 'onSingleInputChange';