vendredi 12 juin 2020

Typescript - Options Object or Builder

So, I'm trying to implement "Options Object" in typescript that I read is an alternative to Java Builder pattern.

I saw that I can use builder, but it seems much more complex to implement than "Options Object" which provides similar thing with less code.

This is something I would like to achieve:

class OptionsObject {
    private readonly name : string;
    private readonly no? : number;

    constructor(o : OptionsObject){
        this.name = o.name;
        this.no = o.no;
    }

    uradi() : void{
        console.log(`Number is ${this.no} and name is ${this.name}`);
    }
}

const p = new OptionsObject({
    name:"asd",
    no:11
} as unknown as OptionsObject); //works but no type-safety
p.uradi();

//standard java builder
//const p2 = new OptionsObjectBuilder().name("asd").no(11).build();

I would like to pass to new OptionsObject only properties that I need. This way as it is now - it works but I have no type safety. I would not like to introduce additional interface, since then I would need to duplicate properties.

Is there any better way to do this with type-safety, or is there any other pattern similar to builder that is adapted to typescript?

Aucun commentaire:

Enregistrer un commentaire