I have a Typescript class that is capable of being validated, resulting in guaranteed field types. However, the class must also be able to accept user input. Is it possible to extract a strict type from this permissible class?
Simplified: I have a class with an implicit interface of {value: string | undefined}
and I am seeking a way to derive {value: string}
automatically. Is this feasible?
To provide more context, here is an example of such a class:
class Validatable {
value: string | undefined = undefined
}
(In my actual implementation, it needs to be a class due to validation requirements, but the specifics of validation are not relevant for this query)
This class can undergo validation as follows:
function getValid (inst: Validatable) {
const errors = validate(inst)
if (errors.length > 0) throw new Error("Invalid")
return inst
}
const inst = new Validatable()
inst.value = "foo"
getValid(inst).value
^-- at this point, the type is string | undefined
however, we know it should be strictly a string
What I aim to achieve is an automatic derivation of the strict interface {value: string}
. Is this within the realm of possibility?