简体   繁体   中英

How to define a lambda function with a return type that can be used later with a generic

I have a class using generics like such -

export class MyClass<T>
{
    constructor( private myCallback:()=>T)
    {
        ...
    }
}

My callback is a lambda fucntion that returns a new object of type T. I'd like to be able to write code inside MyClass as such

let t:T = this.myCallback() ;

however i'm running into build errors. Seems the syntax is broken somewhere but i don't know where. Can anyone help?

The following compiles just fine here :

class MyClass<T> {
  constructor(private myCallback: () => T) {}

  thing(): T {
    const t: T = this.myCallback();
    return t;
  }
}

let s: string = new MyClass<string>(() => "hello").thing();

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