【问题标题】:return type for class function typescript类函数打字稿的返回类型
【发布时间】:2015-08-10 05:19:16
【问题描述】:

我想知道是否可以声明类函数的返回类型,该返回类型将在实例化时通过它的构造函数传递给类。

我使用“creature”类作为生物的通用基础,并将其细节(定义为接口“creatureSpecs”)传递给构造函数。

生物的“行动”功能是可变的,取决于它是什么类型的生物。 'act' 总是会返回一个 'Action' - 它只需要一个特定于生物的代码路径来做到这一点。

所以 A)我可以在类本身上声明通过构造函数传递的函数的返回类型吗?

B) 这是错误的做法吗?

示例代码:

interface Action {type: string; direction: string;}
interface Creaturespec{ energy: number; direction: string; act: Function;        preyseen?: Array<any>};

var Creaturespecs: {[id: string]: Creaturespec } = {}

class creature{
  public energy: number;
  public direction: string; 
  public act: Function; 
  public originChar : string;
  public preyseen: Array<any>;

  constructor(spec: Creaturespec, originChar: string) {
    this.energy = spec.energy;
    this.direction = spec.direction;
    this.act = spec.act;
    this.originChar = originChar
    this.preyseen = spec.preyseen; 
  }
};

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这是一个简化的例子:

    interface Action {
        verb: string;
        /* ? */
    }
    
    interface Spec<T> {
        name: string;
        act(): T;
    }
    
    class Creature<T> {
        constructor(public spec: Spec<T>) {     
        }
    
        getAction(): T {
            return this.spec.act();
        }
    }
    
    
    var dog = new Creature({
        name: 'dog',
        act() {
            return { verb: 'woof', bark: 'bark' }
        }
    });
    
    // b: { verb: string, bark: string }
    var b = dog.getAction();
    

    【讨论】:

    • 谢谢瑞恩,我花了一点时间才得到这个! .最后一个问题-如果我在狗实例化中使用强制转换-即'act(){return {动词:'woof',bark:'bark'}}'-那将使我的动作'type'流过,对吧?
    猜你喜欢
    • 2022-01-12
    • 2021-09-17
    • 1970-01-01
    • 2022-07-07
    • 2021-12-17
    • 2019-07-06
    • 2020-06-29
    • 2020-05-09
    • 2021-06-17
    相关资源
    最近更新 更多