[英]Import JSON file in TypeScript declaration (*.d.ts files)
I am writing a declaration file which should declare a global type and strict to a specific list of string phrases.我正在编写一个声明文件,该文件应声明一个全局类型并严格针对特定的字符串短语列表。
These string phrases are actually part of property keys in an object located in a JSON file.这些字符串短语实际上是位于 JSON 文件中的 object 中属性键的一部分。
Two questions:两个问题:
Object.keys
and Array.map
?是否可以将 JSON 文件导入声明文件并使用基本函数对其进行处理,例如Object.keys
和Array.map
?Let me give you a code example.让我给你一个代码示例。
Let's say we have the following JSON file named data.json
:假设我们有以下名为data.json
的 JSON 文件:
{
"someList": {
"#key1": {"a": 1, "b": 2},
"#key2": "some value",
"#key3": 1234
}
}
Now, I want to create the following declaration file global.d.ts
:现在,我想创建以下声明文件global.d.ts
:
import data from './data.json';
declare global {
type AllowedKeys = Object(data.someList).map(key => key.substr(1));
}
Basically, I need the type to be defined (dynamically as JSON file changes) like this:基本上,我需要像这样定义类型(动态地作为 JSON 文件更改):
type AllowedKeys = "key1" | "key2" | "key3";
Any help or at least guidance would be appreciated.任何帮助或至少指导将不胜感激。
You can have typescript infer a type from data in a json-file.您可以让 typescript 从 json 文件中的数据推断类型。
import data from "./data.json";
export type AllowedKeys = keyof typeof data["someList"];
// This is equivalent to
// export type AllowedKeys = "#key1" | "#key2" | "#key3"
The resulting d.ts
file looks like this:生成的d.ts
文件如下所示:
import data from "./data.json";
export declare type AllowedKeys = keyof typeof data["someList"];
As far as I know, there's no way to manipulate string literals in typescript (ie, removing the #
).据我所知,没有办法在 typescript 中操作字符串文字(即删除#
)。
See those github issues:查看那些 github 问题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.