@rustable/type
Version:
A TypeScript implementation of Rust-like type system with generic support and runtime type information.
52 lines (51 loc) • 2.32 kB
TypeScript
import { Constructor } from './common';
/**
* Creates a class factory that allows instantiation both with and without the 'new' keyword
* @param BaseClass The class to be wrapped
* @param factoryFn Optional custom function that returns any type when called without new.
* If not provided, returns a new instance of BaseClass
* @returns A function that can be called with or without 'new' to create instances
* @example
* // Basic usage:
* class MyClass {
* static helper() { return 'help'; }
* }
* const MyClassFactory = createFactory(MyClass);
*
* // Both ways work:
* const instance1 = MyClassFactory();
* const instance2 = new MyClassFactory();
*
* // Static methods are preserved:
* MyClassFactory.helper(); // returns 'help'
*
* // Custom factory function:
* class Person {
* constructor(name: string) { this.name = name; }
* }
* const factory = createFactory(
* Person,
* (name) => ({ name, timestamp: Date.now() })
* );
*
* const obj = factory('test'); // returns { name: 'test', timestamp: 123... }
* const instance = new factory('test'); // returns Person instance
*/
export declare function createFactory<T extends new (...args: any[]) => any, P extends any[] = ConstructorParameters<T>, R = InstanceType<T>>(BaseClass: T, factoryFn?: (...args: P) => R): T & ((...args: P) => R);
export declare function createFactoryProxy<T extends new (...args: any[]) => any, P extends any[] = ConstructorParameters<T>, R = InstanceType<T>>(BaseClass: T, factoryFn?: (...args: P) => R): T & ((...args: P) => R);
/**
* Creates a factory for a type that can accept generic type parameters.
* This allows for creating parameterized types similar to generics in other languages.
*
* @param baseType The base constructor type to be parameterized
* @returns A factory function that accepts generic type parameters and returns a parameterized type
* @example
* // Create a generic container type
* class Container {}
* const GenericContainer = createGenericType(Container);
*
* // Use the factory to create a specific parameterized type
* const StringContainer = GenericContainer(String);
* const NumberContainer = GenericContainer(Number);
*/
export declare const createGenericType: <T extends Constructor>(baseType: T) => T & ((...generics: Constructor[]) => T);