我有一個帶有一堆方法的介面:
@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
任何想法?
謝謝
uj5u.com熱心網友回復:
您收到此錯誤是因為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';
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/522011.html
標籤:有角度的打字稿角14
