首页 > 解决方案 > 打字稿记录,无需手动键入键

问题描述

我需要一些关于 Typescript Records 的帮助。

我正在寻找一种解决方案,避免手动键入键名作为记录的键类型,但仍为该对象保留智能感知。

智能感知示例

例如:

import { StyleProp, TextStyle } from 'react-native';

//I would like to avoid manually typing dozens of keys here. 
//Can it somehow automatically fetch keys that are already inside the fonts object?
type TFontKeys =
  | 'title'
  | 'subtitle'
  | 'header'
///////

const fonts: Record<TFontKeys, StyleProp<TextStyle>> = {
  title: {
    fontSize: 22,
    fontWeight: '600',
  },
  subtitle: {
    fontSize: 16,
    fontWeight: '600',
  },
  header: {
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 8,
  }}

我知道我可以简单地使用

Record<string, StyleProp<TextStyle>>

但后来我失去了对 fonts.properties 的智能感知

没有智能感知

如果没有为此制作记录,是否还有其他方法可以做到这一点?

谢谢~

标签: typescriptreact-native

解决方案


对象类型不能引用自身,因此您可以使用其他类型创建一个新对象,如下所示:

    import { StyleSheet } from 'react-native'
    
    const fonts = {
      title: {
        fontSize: 22,
        fontWeight: '600',
      },
      subtitle: {
        fontSize: 16,
        fontWeight: '600',
      },
      header: {
        fontSize: 16,
        fontWeight: '500',
        marginBottom: 8,
      },
    }
    
    export const typedFonts = StyleSheet.create<
      Record<keyof typeof fonts, any>
    >(fonts)

然后使用typedFonts作为你的风格:

在此处输入图像描述

您的项目取得成功


推荐阅读