我试图将一个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;
}
value
,而是key
(抱歉我应该更清楚地说明) - Adam James