I have a Vue project in Typescript, and I'm running into an issue regarding the mapping of an Object of Tuples to an Object of Union types.
For a bit of context, I'm working on a Backend endpoint's expected response types. Currently, this endpoint receives 2 values: an enum, and a string. Depending on the enum the response object will change.
This is the current implementation:
const validations = {
email: ['isValid', 'isAvaliable'],
password: ['isMinLengthValid', 'hasUppercase', 'hasLowercase', 'hasSpecialChars', 'hasNumbers'],
iban: ['isValid', 'isRegistered']
} as const
type ValidationsMap = {
[T in keyof typeof validations]: typeof validations[T][number]
}
function validate<T extends keyof ValidationsMap>(type: T, value: string): Record<ValidationsMap[T], boolean> {
// Do something
}
Now the Backend endpoint will receive one more parameter, and the response object will depend on it too.
This is what I've tried, but it's not working:
const validations = {
portal: {
email: ['isValid', 'isAvaliable'],
password: ['isMinLengthValid', 'hasUppercase', 'hasLowercase', 'hasSpecialChars', 'hasNumbers'],
},
payment: {
email: ['isValid'],
iban: ['isValid', 'isRegistered']
}
} as const
type ValidationsMap = {
[S in keyof typeof validations]: {
[T in keyof typeof validations[S]]: typeof validations[S][T][number] // Error: Type 'number' cannot be used to index type...
}
}
function validate<S extends keyof ValidationsMap, T extends keyof ValidationsMap[S]>(service: S, type: T, value: string): Record<ValidationsMap[S][T], boolean> {
// Do something
}
Does anyone know why this doesn’t work?
I thought there might be a limit to how deep it will allow to map a Tuple to a Union, but it doesn't seem to be the case.
This works correctly:
type PortalEmailValidation = typeof validations['portal']['email'][number]