我正在尝试创建一个类型保护--允许将一系列速记css属性转换为它们的普通版本--但这样做时不必在最后将规则转换回keyof SxProps
。
type SxProps = { w?: string; width?: string; h?: string; height?: string; }
const shorthandCssRuleMapping = {
w: 'width',
h: 'height'
} as const;
export function hasKey<K extends string>(
key: K,
object: {}
): object is { [_ in K]: {} } {
return typeof object === "object" && object !== null && key in object;
}
export function convertShorthandRule(rule: keyof SxProps) {
let longHandRule = rule;
if (hasKey(rule, shorthandCssRuleMapping)) {
let pickedShortHandRule = shorthandCssRuleMapping[rule];
// @NOTE: REALLY wish we didn't have to cast here...
longHandRule = pickedShortHandRule as keyof SxProps;
}
return longHandRule;
}
基本上,pickedShorthandRule的类型如下:{} | "width" | "height"
。我很确定这是来自一个不可靠的类型 predicate -但无法确定如何修复它。:P
我真用得着:"width" | "height"
-这样我就可以摆脱演员阵容:as keyof SxProps
救命啊!
1条答案
按热度按时间oknwwptz1#
您可以将
object is { [_ in K]: {} }
更改为object is { [_ in K]: keyof SxProps }
,以确保shorthandCssRuleMapping
中的值始终来自长手键Playground