typescript - 如何为包含键/值对以及嵌套对象的对象/数组定义接口?
问题描述
我正在输入一个本地化库,并且我的目标是对其进行强类型化(因为它将在多个角度应用程序中重复使用)并且 - 同时 - 向后兼容,因此我们不会有重写所有现有的本地化文件。
但是,所述本地化文件的结构让我有点头疼。每个例子:
{
'any-random-key': 'This is a string',
'another-random-key': {
'random-key': 'This is a string'
},
'yet-another-random-key': {
'random-key-2': 'This is a string',
'random-key-3': {
'random-key-4': 'This is a string',
'random-key-5': {
'random-key-6': 'This is a string'
}
}
},
'and-yet-another-random-key': {
'random-key-6': {
'random-key-7': {
'random-key-8': 'This is a string'
},
'random-key-9': 'This is a string'
}
}
}
现在 - 我想我可以说服务接受translations: any
或translations: object
- 但这对我来说有点太随意了(不是双关语)。
所以我尝试使用两个不同的接口:
export interface ITranslation {
[s: string]: string;
}
export interface ITranslations {
[s: string]: ITranslation;
}
然而,这没有any-random-key
说:Type 'string' is not assignable to type 'ITranslation'
所以我调整我的ITranslations
-interface 使它变成
export interface ITranslations {
[s: string]: ITranslation | string;
}
修复了上述错误,但在'and-yet-another-random-key'
说上引入了一个新错误Property ''and-yet-another-random-key'' is incompatible with index signature.
在这一点上,我有点难过。我想要实现的目标(遗留结构的强类型)根本不合理吗?
解决方案
对于任何任意级别的嵌套(换句话说,您的数据对象可以是任意级别的深度),您可以简单地自引用接口,如下所示:
/** @interface */
export interface ITranslations {
[s: string]: ITranslations | string;
}
如果您只想允许 3 级深度嵌套,那么界面将不得不是冗长的:TypeScript 不允许您定义“深度”(即嵌套的程度):
/** @interface */
export interface ITranslations<T = string> {
[s: string]: T | string;
}
/** @type */
export type ITranslationsMax3Levels = ITranslations<ITranslations<ITranslations<ITranslations>>>;
const data: ITranslationsMax3Levels = { ... }
推荐阅读
- amazon-web-services - Amazon UserData 引导脚本无法重新启动 pm2 进程
- javascript - 在ajax发布响应后工作的JQuery脚本不起作用
- javascript - 如何确定鼠标是否不在元素上?
- visual-studio-code - VSCode中带有特殊符号='“'的代码片段
- flutter - 如何在 Flutter 中同时实现 device_preview 和 auto_route 包
- ios - 我将如何遍历所有键以获得特定的子值?
- tensorflow - 在单节点多 GPU 训练中,我应该在哪里存储变量的最佳实践是什么?
- google-apps-script - 为 Add On 项目添加 Google API OAuth 范围
- excel - 如何检查工作表是否存在?
- python - Django 数据库路由器没有路由到正确的数据库