In my TS function, I deserialize JSON into a specific type/object by providing it with a constructor function of that type which reconstructs the object from JSON.
Here is how it looks like:
export function deserializeJSON<T>(JSONString: string, type?: FunctionConstructor, ...
Is there a way to indicate that the argument type: FunctionConstructor
represents the constructor of type <T>
?
UPDATE
Example usage of deserializeJSON
:
const serializedDate = JSON.stringify(new Date);
const deserializedDate = deserializeJSON<Date>(serializedDate, Date);
EDIT
I've discovered that FunctionConstructor
means the constructor of Function, so it might be better to label the argument type
as type: Function
. However, this approach requires casting type to <any>
when using new type
. Is there a way to express something like <T>.constructor
instead?
EDIT
I have created an interface:
interface Constructor<T> extends Function{
new (): T;
new (...args: Array<any>): T;
(...args: Array<any>): T;
prototype: T;
}
This essentially defines a generic newable Function
, but unfortunately, it cannot be assigned to types like DateConstructor. Hence, it's preferable to stick with type: Function
since it accepts all constructors.