[英]Typescript Record without manually typing keys
我需要 Typescript 記錄方面的幫助。
我正在尋找一種解決方案,避免手動鍵入鍵名作為記錄的鍵類型,但仍為 object 保留智能感知。
例如:
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 的智能感知
如果沒有為此制作記錄,是否還有其他方法可以做到這一點?
謝謝~
object 類型不能引用自身,因此您可以使用其他類型創建一個新類型,如下所示:
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
作為您的樣式:
您的項目取得成功
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.