Are you in need of a validator that will flag an error if T2
cannot be assigned to T1
, all before runtime? Well, you can create something like this:
type ValidityWitness<U extends T, T> = U
This can be used as follows:
type T2Validation = ValidityWitness<T2, T1>
If T2
is indeed assignable to T1
, no errors will pop up. However, if the assignment doesn't work, you'll receive an error specifying that T2
does not meet the constraint set by T1
.
Let's demonstrate with some actual types:
interface Master {
key: string;
value: number;
}
interface GoodExtension {
key: 'x';
value: 5;
extra: boolean;
}
type AccurateValidation = ValidityWitness<GoodExtension, Master> // works fine
Note that GoodExtension
isn't explicitly linked to Master
, yet it is validated as a subtype nonetheless. Here's an example where validation fails:
interface FlawedExtension {
key: string;
extra: boolean;
}
type FaultyValidation = ValidityWitness<FlawedExtension, Master> // triggers an error
The compiler struggles to validate FlawedExtension
as a subtype of Master
, and the error message clearly points out the issue:
Type 'FlawedExtension' does not satisfy the constraint 'Master'. Property 'value' is missing in type 'FlawedExtension'.
Hope this explanation proves beneficial! Best of luck!