I'm attempting to write a typescript function for parsing a string containing a range and I'm attempting to allow providing either a constructor or a function as the factory for building the value.
type RangeFactory<T, R> = (start: T, leftInclusive: boolean, end: T, rightInclusive: boolean) => R;
type RangeCtor<T, R> = new (start: T, leftInclusive: boolean, end: T, rightInclusive: boolean) => R;
export function parse<R extends Ranged<T>, T>(text: string,
rangeCtor: RangeCtor<T, R> | RangeFactory<T, R>) {
...
return isConstructor(rangeCtor)
? new rangeCtor(start, leftInclusive, end, rightInclusive)
: rangeCtor(start, leftInclusive, end, rightInclusive);
}
My problem at the moment is in how to actually check if 'rangeCtor' is a constructor method, or if instead it's possible to call rangeCtor the same way regardless of it being a constructor.
Cheers
-- Edit --
One possible way I can think of doing it would be to have a seperate method that takes the constructor and calls parse by wrapping it, but I'd like to avoid that if possible
export function construct<R extends Ranged<T>, T> (text: string,
rangeCtor: RangeCtor<T, R>) {
const factory: RangeFactory<T, R> = (start, leftInclusive, end, rightInclusive) => new rangeCtor(start, leftInclusive, end, rightInclusive);
return parse(text, factory, elementFactory);
}