最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - React Native Nested tuple autocomplete suggests all keys instead of filtering by first key - Stack Overflow

programmeradmin0浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论