【问题标题】:Typescript define type for object will loose static object key (property) suggestionTypescript 为对象定义类型将丢失静态对象键(属性)建议
【发布时间】:2021-04-14 07:08:17
【问题描述】:

代码如下:

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.

不期望: Screenshot

预期: Screenshot - expected

预期行为:

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

喜欢:

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

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

【问题讨论】:

  • 没有建议因为[key: string]
  • ButtonProps 被定义为{ [key: string]: any },这意味着键可以是任何字符串,所以你不能指望静态编译器给你一些建议。我建议你最好用更严格的类型来设计ButtonProps,实际的类型是没用的。
  • 那我怎样才能两者兼得?

标签: javascript reactjs typescript frontend


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 2020-10-11
    • 2022-01-17
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 2016-12-02
    相关资源
    最近更新 更多