#Passing Class as function parameter

17 messages · Page 1 of 1 (latest)

regal talon
#

How can I pass a class as a function parameter so that i can call static methods of the class?

class MyClass {
static staticMethod() { return 0 }
}

function a<M extends MyClass>(C: M) {
  C.staticMethod();
}
#

^ unfornately, interfaces dont allow static methods

interface StaticClass<C> = {
   static staticMethod(): C;
}

craggy delta
#

that's why interfaces don't allow static properties, because it doesn't make sense

#

however, you can have types that describe a class object, and add additional properties to it

#
class Foo {}
type FooClass = typeof Foo; // represents the class Foo itself, not an instance
type OtherFooClass = { new(): Foo }; // a class whose instances are Foo's
#

notice the OtherFooClass type

#

you can add extra properties to it

#
type SomeClass = { new(): Foo, someStaticMethod(): void };
regal talon
#

thanks! One more thing, how can I say that I want to have the type SomeClass, that has the special someStaticMethod on it PLUS all previous instance methods of Foo?

Sort of something like


type SomeClass<C> = {
   ...C, // all instance methods on C
   someStaticMethod(): void 
};
craggy delta
#

hum, are you sure you understand what you are asking?

#

it seems rather unusual to have both the instance properties+methods as weel as the class (static) properties+methods

#

!ts

keen shoalBOT
#
class MyClass {
    public static myStaticProperty: string;
    public myInstanceProperty!: number;
}

type InstanceAndClass<T extends { new(): any }> = T & InstanceType<T>;


declare const c: InstanceAndClass<typeof MyClass>;

c.myInstanceProperty;
// ^? - (property) MyClass.myInstanceProperty: number

c.myStaticProperty;
// ^? - (property) MyClass.myStaticProperty: string
craggy delta
#

@regal talon are you sure it's what you need?

potent hatch
#

FWIW the only thing you were missing in your original code was typeof:

keen shoalBOT
#
class MyClass {
  static staticMethod() { return 0 }
}

function a<M extends typeof MyClass>(C: M) {
  C.staticMethod();
}