简体   繁体   中英

return type for class function typescript

I'm wondering if it's possible to declare the return type of a class function which will be passed to the class on instantiation via it's constructor.

I'm using a 'creature' class as a generic base for a creature and passing it's specifics (defined as interface 'creatureSpecs') into the constructor.

A creatures 'act' function is variable, depending on what kind of creature it is. 'act' will always return an 'Action' though, - it'll just take a creature-specific code path to do that.

So A) Can i declare the return type of a function passed via the constructor, on the class itself?

B) Is this the wrong way to go about it?

Sample code:

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; 
  }
};

Here's a simplified example:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM