I've been working on a TypeScript project where I need to ensure certain constraints on enum values within an object structure. I've come up with the following code that uses mapped types and conditional types to achieve the validation. The code seems to work as intended and doesn't show any errors in my development environment (e.g., VS Code), but I'm not entirely sure if I've implemented it correctly.
The code enforces that the values in the small_companies array should only contain values present in the all_companies array. Can someone please review the code and let me know if it's correctly enforcing these constraints? Additionally, any suggestions for improvement or potential issues that I might have missed would be greatly appreciated.
enum Companies {
Maruti = "Maruti",
Audi = "Audi",
Renault = "Renault",
}
type SmallCompanies<T extends Companies[]> = T[number];
interface CompaniesTypes {
all_companies: Companies[];
small_companies: SmallCompanies<CompaniesTypes["all_companies"]>[];
}
// This will cause a TypeScript error
const companies: CompaniesTypes = {
all_companies: [Companies.Maruti, Companies.Audi],
small_companies: [Companies.Renault],
};
// This will not cause any TypeScript errors
const validCompanies: CompaniesTypes = {
all_companies: [Companies.Maruti, Companies.Audi, Companies.Renault],
small_companies: [Companies.Maruti],
};
I've provided comments within the code to explain its purpose, but I'm particularly interested in knowing if the SmallCompanies type and the CompaniesTypes interface are being used correctly for the validation. Your expertise would be incredibly helpful in ensuring that this code is reliable and error-free for my project. Thank you in advance for your assistance!