Is there a better way to do this?

Is there a better way to do this? (lol)
 
if(typeof (<any>queryOrModel).prototype !== 'undefined' && new (<any>queryOrModel)() instanceof Objection.Model)
queryOrModel can be Objection.QueryBuilder<Schwifty.Model> | Objection.Model

queryOrModel is this case = request.models().Clients

meaning it’s not constructed yet so it seems I can’t queryOrModel instanceof Objection.Model, I have to new queryOrModel() before and in TS it translates to new (<any>queryOrModel)() :-/
You already invited:

Ali

Upvotes from:

new can have side effects, here's a few options.
 
class A {
constructor() { console.log('A constructed') }
}
class B extends A {
constructor() {
super()
console.log('B constructed')
}
}

const justA = A;
const justB = B;

const tests: [ typeof A | typeof B, string][] = [
[ justA, 'justA' ],
[ justB, 'justB' ]
]

for (const [obj, name] of tests) {
console.log(`A.isPrototypeOf(${name}) -> ${A.isPrototypeOf(obj)}`)
console.log(`${name}.prototype instanceof A -> ${obj.prototype instanceof A}`)
console.log(`${name}.prototype === A.prototype -> ${obj.prototype === A.prototype}`)
console.log(`Object.create(${name}.prototype) instanceof A -> ${Object.create(obj.prototype) instanceof A}`)
}
Output:
A.isPrototypeOf(justA) -> false
justA.prototype instanceof A -> false
justA.prototype === A.prototype -> true
Object.create(justA.prototype) instanceof A -> true
A.isPrototypeOf(justB) -> true
justB.prototype instanceof A -> true
justB.prototype === A.prototype -> false
Object.create(justB.prototype) instanceof A -> true
I'd recommend wrapping whatever you choose as a convenience method so you don't come back to this in a couple months and waste time trying to understand it... Signature should look like this: function isObjectionModel(obj: unknown): obj is typeof Objection.Model

If you wanna answer this question please Login or Register