typescript - 创建递归样式对象时的打字稿问题
问题描述
我需要制作一个递归样式对象,它可以支持样式属性和嵌套格式。
我很难解决这个问题,而且我已经尝试了几乎所有可以在 SO 和 google 上找到的解决方案。
interface Properties {
border?: string;
width?: string;
}
//# 1 Type attempt
type TRecursiveProperties = Properties & {
[index: string]: TRecursiveProperties;
};
//# 2 Interface attempt
interface IRecursiveProperties extends Properties {
[index: string]: IRecursiveProperties;
}
const test: TRecursiveProperties = {
border: '1px solid green',
isActive: {
border: '2px solid red',
'&:hover': {
border: '3px solid blue'
}
}
};
我希望 Recursive 属性是一种后备/捕获所有或某种方式来从 Properties 对象中排除键。
我得到的两个错误是
类型别名“TRecursiveProperties”循环引用自身。
“字符串”类型的属性“宽度”不可分配给字符串索引类型“IRecursiveProperties”
有什么想法可以实现吗?
解决方案
我会这样做:
interface Properties {
width?: string;
border?: string;
[selector: string]: string | Properties | undefined;
}
const myStyles: Properties = {
'width': '100px',
' .child': {
'width': '200px',
'border': '1px color blue',
'&:hover': {
border: '1px solid aquamarine',
},
},
};
在这个打字稿资源:https ://basarat.gitbooks.io/typescript/docs/types/index-signatures.html中,搜索“设计模式:嵌套索引签名”以查看非常相似的示例。
推荐阅读
- javascript - 运行@hapi/hapi 给出错误“#meetings = null SyntaxError: Invalid or unexpected token”
- python - 按键事件不会更新while循环内的变量
- rust - 如何使用 cargo 更新 crate 注册表(索引)
- python - TypeError:“float”对象在 Pandas Dataframe Python 中不可迭代
- avro - AVRO 这个名字是怎么来的?
- mysql - MySQL/MariaDB:“GRANT ... IDENTIFIED BY”与“CREATE USER”然后“GRANT”有什么区别?
- asp.net-mvc - 如何使用 Entity Framework Core 显示 3 个表中的数据
- firebase - Flutter Firestore 基于角色的身份验证
- python - 如何为本质上是绑定到 .txt 文件的 .png 的 python 应用程序创建自己的文件类型?
- python - 与 pyperclip 一起使用时,硒中的 .send_keys 会弄乱缩进