TypeScript接口:如何为单个属性指定两个可选键名?
解决TypeScript接口中指定top/bottom可选属性的问题
你原来的写法有误,TypeScript不支持[top | bottom] ?: ...这种语法定义属性,这才导致bottom被判定为不属于IStyles。根据你的需求,分两种场景给出解决方案:
场景1:允许top和bottom同时作为可选属性(符合CSS常规用法)
直接将top和bottom分别声明为可选属性即可,这是最适配CSS命名规则的写法:
interface IStyles { position?: string; top?: string | number; bottom?: string | number; margin?: string | number; padding?: string | number; background?: string | Colors; }
场景2:严格限制只能存在top或bottom中的一个(二选一)
如果需要确保接口实例里最多只有top或bottom其中一个属性,可以用联合类型结合never实现:
type IStyles = { position?: string; top?: string | number; margin?: string | number; padding?: string | number; background?: string | Colors; bottom?: never; } | { position?: string; bottom?: string | number; margin?: string | number; padding?: string | number; background?: string | Colors; top?: never; };
错误原因说明
你写的[top | bottom]不是合法的TypeScript索引签名语法,索引签名要求键的类型是string、number或symbol这类泛型类型,不能直接用字面量的或逻辑指定具体键名,因此TypeScript无法识别bottom为接口的属性,从而抛出错误。
内容的提问来源于stack exchange,提问作者JustBarnt
相关产品推荐
相关产品推荐

