I tried with this but it doesn't work. Foo is just a test of what works. Bar is the real try, it should receive any newable type but subclasses of Object isn't valid for that purpose.
class A {
}
class B {
public Foo(newable: typeof A):void {
}
public Bar(newable: typeof Object):void {
}
}
var b = new B();
b.Foo(A);
b.Bar(A); // <- error here
In Typescript, we have three ways to work with it using: typeof: the keyword helps to check values types, like boolean, string, number, etc. instanceof: the keyword to compare the object instance with a class constructor. type guards: The powerful way to check types using typescript feature language.
The TypeScript docs have a great example of constructor usage: class Greeter { greeting: string; constructor(message: string) { this. greeting = message; } greet() { return "Hello, " + this. greeting; } } let greeter = new Greeter("world");
Parameter properties are declared by prefixing a constructor parameter with an accessibility modifier or readonly , or both. Using private for a parameter property declares and initializes a private member; likewise, the same is done for public , protected , and readonly .
Type keyword in typescript: In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types.
In TypeScript, the syntax for creating custom types is to use the type keyword followed by the type name and then an assignment to a {} block with the type properties.
You can use { new(...args: any[]): any; }
to allow any object with a constructor with any arguments.
class A {
}
class B {
public Foo(newable: typeof A):void {
}
public Bar(newable: { new(...args: any[]): any; }):void {
}
}
var b = new B();
b.Foo(A);
b.Bar(A); // no error
b.Bar({}); // error
If you want to enforce only certain newables, you can specify the constructor's return type
interface Newable {
errorConstructor: new(...args: any) => Error; // <- put here whatever Base Class you want
}
equivalent
declare class AnyError extends Error { // <- put here whatever Base Class you want
// constructor(...args: any) // you can reuse or override Base Class' contructor signature
}
interface Newable {
errorConstructor: typeof AnyError;
}
testing
class NotError {}
class MyError extends Error {}
const errorCreator1: Newable = {
errorConstructor: NotError, // Type 'typeof NotError' is missing the following properties from type 'typeof AnyError': captureStackTrace, stackTraceLimitts
};
const errorCreator2: Newable = {
errorConstructor: MyError, // OK
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With