在 typescript 中使用"in"类型保护

6jygbczu  于 2022-11-30  发布在  TypeScript
关注(0)|答案(1)|浏览(174)

我正在尝试创建一个类型保护--允许将一系列速记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
救命啊!

oknwwptz

oknwwptz1#

您可以将object is { [_ in K]: {} }更改为object is { [_ in K]: keyof SxProps },以确保shorthandCssRuleMapping中的值始终来自长手键

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]: keyof SxProps } {
  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];
    longHandRule = pickedShortHandRule;
  }
  return longHandRule;
}

Playground

相关问题