简体   繁体   中英

Typescript define type for object will loose static object key (property) suggestion

Here is the code:

interface ButtonProps {
  [key: string]: any
}

export const button: ButtonProps = {
  primary: {
    background: theme.background.primary,
    color: theme.color.base,
  },
  base: {
    background: theme.background.base,
    color: theme.color.primary,
  },
}

// button.pr.. 
// 👆 When I press primary, the vscode static suggestion won't show `primary` or `base` keys, because [key: string] could be any string.

Not expected: Screenshot

Expected: Screenshot - expected

Expected Behavior:

Suggestion or static type check for any properties that types defined also manually added keys.

like:

interface ButtonProps {
 primary: ...,
 [key: string]: ...
}
const button: ButtonProps = {
 secondary: ...
}

button.primary // ✅
button.secondary // ✅
button.third // Okay, but no suggestion.

I actually ran into a similar situation myself recently. The issue is that you want to get the narrow type of the object your defining while ensuring it extends the broader type. To fix this, you can create a function that just returns its input but infers it's type.

interface ButtonProps {
  primary: {background:string, color:string};
  [key: string]: any;
}

const createButtonProps = <T extends ButtonProps>(props: T) => props;

export const button = createButtonProps({
  primary: {                               // primary is required
    background: theme.background.primary,
    color: theme.color.base,
  },
  base: {
    background: theme.background.base,
    color: theme.color.primary,
  },
});

// You'll now see intellisense for button.primary & button.base

As a bonus, if you ever need to get the exact value types in the object as well, which was the case for me, you can add as const to the end of the object you pass to the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM