簡體   English   中英

"動態訪問 TypeScript 類的方法"

[英]Dynamically access methods of class TypeScript

我正在嘗試使用先前在 TypeScript 中設置的變量的值動態訪問類的方法。

與此類似的東西:

class Foo {
    bar(){ }
}

var methodName = "bar";
var fooBar = new Foo();

fooBar.methodName(); // I would like this to resolve to fooBar.bar();

我們只需要離開強類型(和檢查)世界,只使用 JavaScript 風格(這仍然很有用,例如在這些情況下)

fooBar[methodName]();

我相信一個界面<\/a>會在這里對您進行分類...

interface FooInterface {
  bar: () => void
  // ...other methods
}

class Foo implements FooInterface {
  bar() {
    console.log('bar')
  }
  // .. other methods omitted
}

const foo = new Foo()

// good 
foo['bar']

// Element implicitly has an 'any' type because expression of type '"barry"' can't be used to index type 'Foo'.
//  Property 'barry' does not exist on type 'Foo'.
foo['barry']

let method: keyof FooInterface

// good
method = 'bar'
foo[method]()

// Type '"barry"' is not assignable to type 'keyof FooInterface'.
method = 'barry'
foo[method]()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM