如何在TypeScript中获得对象键的自动完成功能

问题描述 投票:0回答:1

我目前有这种类型

export type Styles = Record<string, Style>

我这样使用它

// Button.styles.ts
const styles: Styles = {
  primary: ({ colors }) => ({
    backgroundColor: colors.primary,
  }),
  secondary: ({ colors }) => ({
    backgroundColor: colors.secondary,
  }),
}

但是当我将其导入另一个文件时,不会自动完成

import styles from './Button.styles.ts'

// styles.
// I get nothing if I start typing this, but I want to see a list of "primary, secondary"

基本上,我想推断出它的键,以便在使用对象时得到自动完成功能

typescript key record type-inference
1个回答
0
投票
我认为注释类型是多余的。您可以删除Styles类型,它将为

inferred。

如果仍要注释,则类型应为:

// Button.styles.ts type StyleParams = { colors: { primary: string, }, secondary: string, }; type Styles = { primary(params: StyleParams): string, secondary(params: StyleParams): string, }; const styles: Styles = { primary: ({ colors }) => ({ backgroundColor: colors.primary, }), secondary: ({ colors }) => ({ backgroundColor: colors.secondary, }), };

© www.soinside.com 2019 - 2024. All rights reserved.