I am looking for a way to restrict the construction of a class within a module to only be possible through a helper function from that same module. This would prevent any external users of the class from constructing it without using the designated helper function.
For example, the usage could look like this:
//module: email.ts
export class Email {
//implementation details
}
export function tryParse(x: string): Email | null {
//implementation details
}
Later on, I want to utilize it in this manner:
//module: email_usage.ts
import {Email, tryParse} from "./email.ts"
//works
let x?: Email = tryParse("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c0aab5a8b580b9a1a8afafeea3afad">[email protected]</a>")
//but this should fail with an compiler error
let y: Email = new Email("foo")
I have come up with a solution for the above scenario, but I feel like it's quite unconventional.
export class Email {
//I need to make the constructor protected here so it cant be accessed outside
protected constructor(x: string) {
this._value = x
}
private _value: string
get Value () {
return this._value
}
}
//then I create a "Factory" class that extends from Mail so I have access to the protected constructor
class EmailFactory extends Email {
// and then I create a "public" static method to finally create an Email instance
static create(x: string): Email {
return new Email(x)
}
}
export function tryParse(x: string): Email | null {
return EmailFactory.create(x)
}
I am a bit confused that there is no specific access modifier for internal module access (or perhaps I haven't found it yet). Do you have any other suggestions on how to tackle this challenge?