如何在Typescript中确定字符串是否为接口的键值?

4
我试图将一个CSS字符串转换成React.CSSProperties对象,但在升级到Typescript 3.5.3时遇到了类型错误。
简而言之,如何将字符串映射到接口允许的属性。
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;
}
2个回答

0

最后我只是强制执行并忽略了 TypeScript 的错误 :-/


0

您之所以会收到此错误,是因为您尝试分配的值不等于允许的值之一:"-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;

但我不建议这样做。


不是 value,而是 key(抱歉我应该更清楚地说明) - Adam James

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