oop - Describing a function parameter that takes a class as an argument in TypeScript -
i want write function parse class type (the class, not instance) function instantiate instance based on parameter.
this best explained example:
//all possible paramter types must inherit base class class base { public name : string = ''; } //these possible classes parsed function class foo extends base { constructor() { super(); console.log("foo instance created"); } } class bar extends base { constructor() { super(); console.log("bar instance created"); } } //this function should take class inherits 'base' paramter - create instance function example(param : ?????????) : base //i don't know type 'param' should { return new param(); //create instance?? how do } //this should output - if worked (but doesn't) example(foo); //logs "foo instance created"" example(bar); //logs "foo instance created"" //so if worked, become possible this: let b : foo = example(foo); let c : bar = example(bar);
so questions is: type param 'example' function be? , how create instance of param within function.
note, if question duplicate apologise - don't know technical name process difficult research.
you want this.
function example<t extends base>(param: new () => t): t { return new param(); }
we know you'll have some type base
. we're going name t
, , we'll t extends base
enforce that.
we know param
construct t
no parameters. can write new () => t
describe that.
basically way think class has both instance side , static side (also called "constructor" side). in example, base
, foo
, , bar
on own have static side.
the static side each of them consists of static members specify (and there aren't in case), along construct signature. in case, example
takes constructor expects no arguments, , produces subtype of base
.
Comments
Post a Comment