Reactjs 如何确定字符串是否是Typescript中接口的键?
我正试图将CSS字符串转换为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
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错误:-/它不是
值
而是键
(很抱歉,我应该更好地指定它)