约束类型,同时仍保留原始类型吗?

问题描述 投票:0回答:1
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

很高兴介绍其他类型和方法来实现我的目标。

reactjs typescript jss
1个回答
0
投票

不能同时约束变量的类型和推断其类型。通常的方法是使用一个函数,该函数可以具有受约束和推断的类型参数:

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; 

Playground Link

© www.soinside.com 2019 - 2024. All rights reserved.