代码之家  ›  专栏  ›  技术社区  ›  doberkofler

如何根据函数返回的对象指定类型

  •  1
  • doberkofler  · 技术社区  · 6 年前

    如果我用构造函数创建一个对象

    function Person(name: string) {this.name = name;}
    

    function hello(person: ???): string {
       return 'hello ' + person.name;
    }
    
    const person = new Person('John');
    hello(person);
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Ivan Gabriele    6 年前

    您只需在接口中描述构造函数,就像在普通类实现中一样,并在您的应用程序中使用它 hello 功能:

    /* @flow */
    
    interface IPerson {
      name: string;
    }
    
    function Person(name: string) {
      this.name = name;
    }
    
    function hello(person: IPerson): string {
      return 'hello ' + person.name;
    }
    
    const person = new Person('John');
    hello(person);
    

    不过,我建议不要使用构造函数而不是常规类,因为流中的接口点将由类实现,以便对它们进行类型保护:

    class Person implements IPerson {}