typescript - 打字稿记录,无需手动键入键
问题描述
我需要一些关于 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 的智能感知
如果没有为此制作记录,是否还有其他方法可以做到这一点?
谢谢~
解决方案
对象类型不能引用自身,因此您可以使用其他类型创建一个新对象,如下所示:
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
作为你的风格:
您的项目取得成功
推荐阅读
- javascript - 数月经验 - Javascript
- angular - 我如何在同一个角度项目中实现 2 个 html 主题
- sql - 对 Presto 中的所有按值分组的值执行按位运算
- linq - 将复杂的 IQueryable LINQ 重构为子方法
- javascript - Recaptcha v3 有很多误报
- testing - 为什么 radamsa 不生成请求数量的 testacase?
- java - pdf结果格式错误
- json - Apache Druid – 在平面 JSON 数据中摄取多个对象仅返回单行
- r - R Shiny:numericInputs 使用 observeEvent 相互更新
- c# - 如何从 XmlDocument 中删除某个元素?