Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 如何确定字符串是否是Typescript中接口的键?_Reactjs_Typescript_Generics_Types_Deserialization - Fatal编程技术网

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

Reactjs 如何确定字符串是否是Typescript中接口的键?,reactjs,typescript,generics,types,deserialization,Reactjs,Typescript,Generics,Types,Deserialization,我正试图将CSS字符串转换为React.cssprroperties对象,但在Typescript升级到3.5.3时出现键入错误 TLDR;如何将字符串映射到接口允许的属性 export function styleStringToCSSProperties(style: string | null) { const out: React.CSSProperties = {}; if (!style) return null; const properties = styl

我正试图将CSS字符串转换为
React.cssprroperties
对象,但在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;
}

出现此错误是因为您尝试分配的值不等于允许的值之一
“-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;

但我不建议这样做。

我最终只是强制执行它并忽略了typescript错误:-/

它不是
而是
(很抱歉,我应该更好地指定它)