【问题标题】:How to get autocomplete for object keys in TypeScript如何在 TypeScript 中自动完成对象键
【发布时间】:2020-03-21 17:28:48
【问题描述】:

我目前有这种类型

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】:

    我认为注释类型是多余的。 您可以删除Styles 类型,它将被推断

    如果还想注释,类型应该是:

    // 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,
      }),
    };
    

    【讨论】:

      【解决方案2】:

      另一种方式(虽然它本身不使用对象:

      export function primary({ colors }) => { ... }
      export function secondary({ colors }) => { ... }
      export const something = {};
      

      然后,您可以在另一个文件中将它们全部导入:

      import * as everything from "./Button.styles";
      
      everything.secondary({ colors });
      

      现在:everything. 应该建议每个导出的属性(主要、次要、某些东西等)自动完成

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-06
        • 1970-01-01
        • 2020-04-02
        • 2012-09-22
        • 2021-08-14
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多