Typescript接口 - 一个属性有两个可能的键名

3

我有这个接口,想知道是否有可能指定键值能够是潜在的名称。但是,我仍然收到引用错误,说 "bottom" 不属于 IStyles。我对使用typescript还很陌生,在stackoverflow上搜索时,我没有立刻找到与我所需内容相关的其他答案,如果已经有解决方法而我没有注意到,我很抱歉。

我想要在我的Svelte项目中实现类似于这样的功能,因为这些键名显然是css名称,所以我必须使用真正的名称。

interface IStyles
    {
        position?: string;
        [top | bottom] ?: string | number;
        margin?: string | number;
        padding?: string | number;
        background?: string | Colors;
    }

虽然这并没有回答你的问题,但是重新声明CSS类型的原因是什么?据我所知,这方面有许多可用的选项。 - Etheryte
@Etheryte 我在Svelte中制作了一个简单的组件,其中包含一个样式属性,我想传递一组特定的样式来控制其位置、大小和颜色。除了通过props传递值和创建内联样式之外,Svelte没有办法使用css来定位组件。至少从我所发现的情况来看。最坏的情况是,我的问题的答案是否定的,我只是在我的界面底部有额外的行。编辑:就像我说的,我对typescript还很陌生,我不知道typescript已经有了CSS的类型定义...所以让我研究一下...哈哈 - JustBarnt
你的目标是将接口与topbottom键中的一个进行关联,而不是两个都连接吗? - tymzap
@tymzap 我的目标是它可以是其中之一,但不是其他选项。但我知道你的意思。有了这个观点,我最好是都包括。 - JustBarnt
1
“要么这个,要么那个,但没有其他选择。” 这是什么意思?这是否意味着“异或”?如果是这样,那么您需要像这样的联合类型。如果您的意思是“包括或”,那么您可以将两个键都放在一个接口中,就像这样。如果您不是指任何这些(不确定“但没有其他选择”应该意味着什么),您能否详细说明一下? - jcalz
我是指包容性的,但我只是想知道是否有一种方法可以在一行中完成所有操作。但感谢您提供这两个示例! - JustBarnt
2个回答

1

如果我正确理解了你的问题,你希望topbottom属性是互斥的。

这在TypeScript中是可能的,但只能使用"type"而不是"interface",但大多数情况下两者可以非常相似地使用。所以也许这对你有用:

type TopOrBottom = { top?: string | number; bottom?: undefined } | { top?: undefined; bottom?: string | number }

type IStyles = TopOrBottom & {
    position?: string;
    margin?: string | number;
    padding?: string | number;
    background?: string;
};

const validTop: IStyles = { top: 123 };
const validBottom: IStyles = { bottom: '12px' };
const invalid: IStyles = { bottom: '12px', top: 12 }; // TS error

请点击这里


0

你不能这样声明属性。

你可以将常见的键分组到一个对象中,然后使用 交叉类型 创建更复杂的类型。类似于这样:

const Common = {
  top: 0,
  bottom: 0,
};

type IStyles = {
  position?: string;
  margin?: string | number;
  padding?: string | number;
  background?: string | Colors;
} & {  
  [Prop in keyof typeof Common]: string | number;
}

let a: IStyles = {
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接