import { CSSProperties } from 'react';
type StyleRulesType = Partial<CSSProperties>
type StylesDefinition = { [key: string]: StyleRulesType };
const styles: StylesDefinition = {
list: {
position: 'relative',
},
listCount: {
fontStyle: 'italic'
}
}
type StyleKeys = keyof typeof styles;
我试图将样式限制为仅包含CSSProperties标签和值的子项,这通过StylesDefinition约束进行。
我正在尝试将键设为“列表” | 'listitem',当样式不受StylesDefinition约束时可以使用。
我想约束以帮助填充stylevariables和值,同时我希望能够在引用styles对象时进行类型检查,因此我只能使用styles.list和styles.listCount
很高兴介绍其他类型和方法来实现我的目标。
不能同时约束变量的类型和推断其类型。通常的方法是使用一个函数,该函数可以具有受约束和推断的类型参数:
import { CSSProperties } from 'react';
type StyleRulesType = Partial<CSSProperties>
type StylesDefinition = { [key: string]: StyleRulesType };
function createStyleDefinition<T extends StylesDefinition>(o: T) {
return o;
}
const styles = createStyleDefinition({
list: {
position: 'relative',
},
listCount: {
fontStyle: 'italic'
}
})
type StyleKeys = keyof typeof styles;