reactjs - 如何确定字符串是否是 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;
}
解决方案
您收到此错误是因为您尝试分配的值不等于允许的值之一"-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;
但我不建议这样做。
推荐阅读
- modelica - 在 Modelica 中将逆变器与 smpm 连接时的仿真结果错误
- javascript - 在 javascript 中设置多案例倒数计时器时遇到问题
- powerbi - Power BI 如果为空,则输入值
- swift - 键盘出现时更改 ScrollView 插图
- angular - 翻译文件中的翻译和理解按钮
- php - 如何从网页PHP将本地pdf文件打印到另一个单元
- c# - 如何与 SSO 服务对话并打开 URL
- ios - 在 iOS 共享扩展中使用 React Native (0.60.4)
- clips - 如何在尝试 CLIPS 中所有可能的组合的多槽字段中求和整数
- c# - UWP CommandBar SecondaryCommand collides with AppBarButton Flyout