简体   繁体   English

描述 typescript .d.ts 文件的嵌套对象

[英]Describing a nested object for typescript .d.ts file

In my project, I'm importing an object.在我的项目中,我正在导入一个对象。 That object is created by a function so the IDE has no clue what keys are on it (they're dynamic based on the config provided).该对象是由一个函数创建的,因此 IDE 不知道它上面有什么键(它们是动态的,基于提供的配置)。 My thought is that I can generate a .d.ts file that describes the object so people looking to know what keys are on it, can find them with code completion in the IDE.我的想法是我可以生成一个.d.ts文件来描述该对象,以便人们可以在 IDE 中通过代码.d.ts找到它们。

// dynamicObject.js
export default makeAnObject(config);
// useObject.js
import someObject from './dynamicObject.js';

const result = someObject.| (code editor dropdown of keys here)

On one other note, I'm interested in not having the .d.ts file in the same directory as these files.在另外一个音符,我感兴趣的是具有.d.ts在同一个目录中这些文件的文件。 I assume the tsconfig.json can handle this, I just have no clue what the syntax for the .d.ts file would look like.我假设tsconfig.json可以处理这个,我只是不知道.d.ts文件的语法是什么样的。 Typescript is hugely foreign to me and the docs are not helpful.打字稿对我来说非常陌生,文档也没有帮助。

For my dynamicObject.d.ts file, I started with something like this对于我的dynamicObject.d.ts文件,我从这样的事情开始

declare namespace someObject {
   interface oneKey {
      nestedKey: string
   }
}

But the code editor still has no clue what the object composition is.但是代码编辑器仍然不知道对象组合是什么。 I'm not sure if it's the way I'm writing the .d.ts file or something I'm missing in the tsconfig.json ?我不确定这是我编写.d.ts文件的方式还是我在tsconfig.json缺少的tsconfig.json

EDIT : Going to include my tsconfig.json as the first answer didn't work.编辑:要包含我的tsconfig.json作为第一个答案不起作用。 Looking to have the most basic config, but I can imagine it might be missing more:希望拥有最基本的配置,但我可以想象它可能缺少更多:


{
    "compileOnSave": true,
    "compilerOptions" : {
       "baseUrl": "./",
       "paths": {
           "*" : ["myCustomTypings/**.d.ts"]
       }
    }
}

EDIT2 I've temporarily moved the .d.ts file in the same directory as the dynamicObject.js (named dynamicObject.d.ts ) and now the IDE can tell it's typeof someObject but can't tell the object's structure. EDIT2我暂时将.d.ts文件移动到与dynamicObject.js (名为dynamicObject.d.ts )相同的目录中,现在 IDE 可以判断它是typeof someObject但不能判断对象的结构。 How do I describe the object in dynamicObject.d.ts ?如何在dynamicObject.d.ts描述对象?

It's need to declare typeRoots in tsconfig.json.需要在 tsconfig.json 中声明 typeRoots。

Below is example下面是例子

{
  "compilerOptions" : {
    "typeRoots" : [ "./node_modules/@types", "./src/types"]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM