我正在嘗試使用 es6 類創建類似服務的命令,如下所示:
class Person {
run(){
console.log("running");
}
walk(){
console.log("walking");
}
talk(){
console.log("talking");
}
execute(name: string){
this[name]()
}
}
const me = new Person();
me.execute('run');
me.execute('walk');
me.execute('talk');
這是完全有效的,但打字稿的this[name]一部分是咆哮:
TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Person'.
在這種情況下,如何將“name”引數定義為 Person 的類成員型別?
uj5u.com熱心網友回復:
鑒于鍵可以是除execute自身之外的任何類鍵,您可以按如下方式定義引數型別:
execute(name: Exclude<keyof Person, 'execute'>){
this[name]();
}
你可以在這個TypeScript playground上看到它的運行情況。
uj5u.com熱心網友回復:
定義名稱型別如下
execute(name: "talk" | "walk" | "run") {
this[name]()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330848.html
上一篇:如何將所有例外配置為“任何”型別
