Error: Cannot invoke an expression whose type lacks a call signature

后端 未结 8 2068
执笔经年
执笔经年 2020-12-02 17:50

I am brand new to typescript, and I have two classes. In the parent class I have:

abstract class Component {
  public deps: any = {};
  public props: any = {         


        
相关标签:
8条回答
  • 2020-12-02 18:36

    Add a type to your variable and then return.

    Eg:

    const myVariable : string [] = ['hello', 'there'];
    
    const result = myVaraible.map(x=> {
      return
      {
        x.id
      }
    });
    

    => Important part is adding the string[] type etc:

    0 讨论(0)
  • 2020-12-02 18:37

    I think what you want is:

    abstract class Component {
      public deps: any = {};
      public props: any = {};
    
      public makePropSetter<T>(prop: string): (val: T) => T {
        return function(val) {
          this.props[prop] = val
          return val
        }
      }
    }
    
    class Post extends Component {
      public toggleBody: (val: boolean) => boolean;
    
      constructor () {
        super()
        this.toggleBody = this.makePropSetter<boolean>('showFullBody')
      }
    
      showMore (): boolean {
        return this.toggleBody(true)
      }
    
      showLess (): boolean {
        return this.toggleBody(false)
      }
    }
    

    The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

    The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

    Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

    0 讨论(0)
提交回复
热议问题