0

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);
}
  • It's tricky. `new (() => {})` throws, `class A{} A()` throws, `new function () { return 5; }` will silently return something unexpected. You might `try { return ctorOrFn(...args) ;} catch{ return new ctorOrFn(...args); }`. Unfortunately, if the class was transpiled from ES5, this will not behave correctly. You will also run into trouble with builtins like `Date` – Aluan Haddad Jul 24 '20 at 01:16
  • The real solution is going to be: don't accept such a union. Just take a callback function as an argument, and if someone has a constructor they can wrap it themselves with an arrow function. – kaya3 Jul 24 '20 at 01:19
  • I realized this already has an answer. – Aluan Haddad Jul 24 '20 at 01:20

0 Answers0