Z
Zod•17mo ago
Steve

No I should just be less lazy 🙂

No, I should just be less lazy 🙂
6 Replies
Steve
SteveOP•17mo ago
@Scott Trinh I basically want to create class instances from schema's, but not sure if it is any good to do.
Scott Trinh
Scott Trinh•17mo ago
Oh, I think I understand. Yeah nothing built in but you can certainly use Zod in your constructor to do a lot of what you would normally do in a constructor.
Steve
SteveOP•17mo ago
@Scott Trinh There is something built-in 🙂 .transform does it with ease
Scott Trinh
Scott Trinh•17mo ago
Hmm, maybe I'm just not understanding the question after all, but glad that works!
Steve
SteveOP•17mo ago
Yeah so I m basically building up a class instance using transform
import {z} from "zod";

class TestClass {
constructor(
public testProp: string
) {

}

public getTestProp(): string { return this.testProp; }
}

const TestClassZSchema = z.object({
testProp: z.string()
}).strict().transform((dto): TestClass => new TestClass(dto.testProp))

const instance = TestClassZSchema.parse({ testProp: '123' });

console.log(instance.getTestProp());
import {z} from "zod";

class TestClass {
constructor(
public testProp: string
) {

}

public getTestProp(): string { return this.testProp; }
}

const TestClassZSchema = z.object({
testProp: z.string()
}).strict().transform((dto): TestClass => new TestClass(dto.testProp))

const instance = TestClassZSchema.parse({ testProp: '123' });

console.log(instance.getTestProp());
Scott Trinh
Scott Trinh•17mo ago
Ahh, gotcha. I was thinking the other way around like:
class TestClass {
public testProp: string;
constructor(
testProp: string
) {
this.testProp = z.string().parse(testProp);
}

public getTestProp(): string {
return this.testProp;
}
}

const instance = new TestClass("123");
class TestClass {
public testProp: string;
constructor(
testProp: string
) {
this.testProp = z.string().parse(testProp);
}

public getTestProp(): string {
return this.testProp;
}
}

const instance = new TestClass("123");
Basically "hide" Zod within the constructor so the consumer doesn't need to think about the parsing, but that definitely has a different public type interface (unknown vs. string).
Want results from more Discord servers?
Add your server