gale/type-experiments-02.ts

22 lines
657 B
TypeScript
Raw Normal View History

2024-08-02 14:45:14 -04:00
type OriginalType = {
key1: { sub1: string; sub2: string };
key2: { subA: string; subB: string };
};
type ValidKeys = keyof OriginalType;
type ValidSubKeys<K extends ValidKeys> = keyof OriginalType[K];
type FixedLengthArray<T, L extends number> = [T, ...T[]] & { length: L };
type EnforcedRecord<L extends number> = {
[K in ValidKeys]: FixedLengthArray<ValidSubKeys<K>, L>;
};
// Example usage:
const example: EnforcedRecord<2> = {
key1: ['sub1', 'sub2'], // Valid
key2: ['subA', 'subB'], // Valid
// key1: ['sub1'], // Invalid, TypeScript will give an error
// key2: ['subA', 'subB', 'subC'], // Invalid, TypeScript will give an error
};