首页 > 解决方案 > 如何确定字符串是否是 Typescript 中的 keyof 接口?

问题描述

我正在尝试将 CSS 字符串转换为React.CSSProperties对象,但在将 Typescript 升级到 3.5.3 时出现输入错误。

TLDR;如何将字符串映射到接口允许的属性

export function styleStringToCSSProperties(style: string | null) {
   const out: React.CSSProperties = {};

   if (!style) return null;

   const properties = style.split(';');
   if (!properties.length) return null;

   for (const property of properties) {
       const [key, value] = property.split(':');

       // Error here because I'm assuming the type checker sees the 
       // 'string' type output of 'camelCase' and because any string
       // is not limited to the exact possibilities in the error msg
       // below.  I was thinking of checking if the value of the output
       // of 'camelCase' is one of the allowed interface keys, but I 
       // can't find a way to do that


      // `Type 'string' is not assignable to type '"-moz-initial" | 
      // "inherit" | "initial" | "revert" | "unset" | undefined'`

       out[camelCase(key) as keyof React.CSSProperties] = value;

       // ^^^^ Brorked
  }

 return out;
}

标签: reactjstypescriptgenericstypesdeserialization

解决方案


您收到此错误是因为您尝试分配的值不等于允许的值之一"-moz-initial" | "inherit" | "initial" | "revert" | "unset" | undefined

编辑

它也可能是由类型检查引起的。我刚刚注意到您的价值来自字符串拆分。这意味着它也是一个字符串。

这意味着您在一侧有一个字符串,而在另一侧有一组允许的值。Typescript 不会喜欢它。

你可以尝试强制你的字符串类型做类似的事情

out[camelCase(key) as keyof React.CSSProperties] = value as typeof (out[camelCase(key) as keyof React.CSSProperties]);

最坏的情况下,您可以将您的价值转换为any

out[camelCase(key) as keyof React.CSSProperties] = value as any;

但我不建议这样做。


推荐阅读