gale/type-experiments-03.ts

28 lines
748 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>;
};
const createTable = <T extends { length: number }>(
cols: T,
rows: EnforcedRecord<T['length']>
) => {
return { cols, rows };
};
// Example usage:
const cols = ["a", "b", "c"] as const;
const table = createTable(cols, {
key1: ['sub1', 'sub2', 'sub1', 'sub1'], // invalid because too long
key2: ['subA', 'subB', 'sub1'], // invalid because bad key
});