To achieve compilation at compile time, one must meticulously define the Age
type. Although it requires a significant amount of typing, it provides complete type-level verification.
type AgeTo15 = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15;
type AgeAbove15 = 15 | 16 | 17 | 18 | 19 | 20 | 21; // and so on up to 100 :)
// defining two versions of our custom data type
type To15Data = {
Name: string,
Age: AgeTo15,
}
type Above15Data = {
Name: string,
Age: AgeAbove15,
Flag: number,
}
type Data = To15Data | Above15Data;
const el: Data = {
Name: 'Name',
Age: 10,
} // valid
const el2: Data = {
Name: 'Name',
Age: 20,
} // invalid
const el3: Data = {
Name: 'Name',
Age: 20,
Flag: 1
} // valid
const arr: Data[] = [
{ Name: "ABC", Age: 20},
{ Name: "XXX", Age: 15}
]; // invalid
const arr2: Data[] = [
{ Name: "ABC", Age: 20, Flag: 1},
{ Name: "XXX", Age: 15}
]; // valid