I am working on a TypeScript utility with react native that extracts nested keys as tuples to be used in a function. The type is supposed to provide autocomplete suggestions that are dynamically filtered based on the first selected key. However, TypeScript's autocomplete is suggesting all possible second-level keys instead of only the relevant ones under the selected first key.
React Native Component Playground
Here is a minimal example of my issue:
interface MyTheme {
colors: {
secondary: string;
tertiary: { light: string; main: string; dark: string };
gray: {
900: string;
800: { mor: string; dark: string; pink: string };
700: string;
};
constant: { white: string; black: string };
};
}
export type NestedKeysArray<T> = T extends object
? {
[K in keyof T]: K extends string | number
? T[K] extends string
? [`${K}`]
: T[K] extends object
? [`${K}`, ...NestedKeysArray<T[K]>]
: never
: never;
}[keyof T]
: never;
const loadingColorHandler = (color: NestedKeysArray<MyTheme['colors']>) => {
console.log(color);
};
// ❌ Unexpected behavior:
// When typing `loadingColorHandler(['tertiary', ''])`, TypeScript suggests `light, main, dark` (✅ expected),
// but also `white, black, 900, 800, 700` (❌ unexpected).
loadingColorHandler(['tertiary', 'black']); // This should be a type error
When entering the first key, the second key should only suggest the properties that belong to that first key.
Input | Expected Suggestions | Actual Suggestions (Incorrect) |
---|---|---|
['gray', ''] | '900', '800', '700' | '900', '800', '700', 'light', 'main', 'dark', 'white', 'black' |
['tertiary', ''] | 'light', 'main', 'dark' | Includes unrelated keys |