#How to dynamically change input type in a class method
1 messages · Page 1 of 1 (latest)
why are those two fields static? is there a way they can be instance properties instead?
this snippet is smaller version of my project, where i am creating classes to perform crud operations on the dynamoDB table.
i have many models, like User, Comment, Blog etc, i dont want to write same logic in each factory class of every model, thats why i am creating a BaseFactory first, defining all the methods here, to create specific factory all i will have to do is
class UserFactory extends BaseFactory<typeof userMock, "username"> {
static hashKey = "username";
static Model = UserModel;
static mock = userMock;
}```
is there any fix for line 31 ?
you can think of type parameters on classes as like type parameters for the constructor. they are applied to instances of the class, not static stuff
trying to somewhat-directly translate what you attempted, here's one idea:
Preview:```ts
const makeBaseFactory = <M, K extends keyof M>() =>
class BaseFactory {
static Mock: M
static hashKey: K
_body: Partial<M> = {}
static body(obj: Partial<M>) {
const inst = new t
...```
that might look a big weird depending on how familiar you are with how classes work in JS/TS, so let me know if you have any questions
personally though i'd probably try to avoid all these factories and just use normal constructors
(i'm not a fan of complex OOP stuff in general, i find it makes the actual logic hard to follow and results in overly-tight coupling)
in your real code what does update actually do?
same here, i dont want these classes, but isn't it only the way for builder pattern, i love syntaxes like MyClass.method1(...).method2().exec()
my original project code here
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
@knotty mortar Here's a shortened URL of your playground link! You can remove the full link from your message.
Preview:```ts
import "server-only"
import {ModelType} from "dynamoose/dist/General"
import {AnyItem} from "dynamoose/dist/Item"
import {BaseSerializer} from "../serializers/base.serializer"
import {MentorMock} from "../models/mentor.model"
import {MentorModel} from ".."
...```
if that's all you want and you prefer to never write new, you don't need classes at all, just functions that return objects
i suspect these may not really be "factories" in the typical usage of that term, really just base classes. do you eventually have class User extends UserFactory in your code?
or maybe there is no such thing as a User/Mentor class, just those factories?
here's a classless example:
Preview:ts const makeModel = <M, K extends keyof M>() => ({ body(obj: Partial<M>) { return { update(pk: M[K]) { // dynamic input type based on K console.log("primary Key: ", pk) return Math.random() > 0.5 ? false : true }, } }, ...