首页 > 解决方案 > Typescript 为对象定义类型将丢失静态对象键(属性)建议

问题描述

这是代码:

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.

不期望: 截图

预期: 屏幕截图 - 预期

预期行为:

对定义类型的任何属性的建议或静态类型检查也手动添加了键。

像:

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

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

标签: javascriptreactjstypescriptfrontend

解决方案


实际上,我最近自己也遇到了类似的情况。问题是您希望获得您定义的对象的窄类型,同时确保它扩展更广泛的类型。要解决此问题,您可以创建一个仅返回其输入但推断其类型的函数。

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 const到传递给函数的对象的末尾。


推荐阅读