#Passing Class as function parameter
17 messages · Page 1 of 1 (latest)
^ unfornately, interfaces dont allow static methods
interface StaticClass<C> = {
static staticMethod(): C;
}
right, because interfaces should describe common properties or behaviors
static refers to the class itself and is for attributes unique to it, and is by definition the complete opposite of an interface
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 };
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
};
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
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
@regal talon are you sure it's what you need?
FWIW the only thing you were missing in your original code was typeof:
class MyClass {
static staticMethod() { return 0 }
}
function a<M extends typeof MyClass>(C: M) {
C.staticMethod();
}