Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
883 views
in Technique[技术] by (71.8m points)

typescript - Where should I place custom .d.ts files?

I'm trying to provide typings for the package that does not have them:

error TS7016: Could not find a declaration file for module 'inputmask-core'. './node_modules/inputmask-core/lib/index.js' implicitly has an 'any' type.
Try `npm install @types/inputmask-core` if it exists or add a new declaration (.d.ts) file containing `declare module 'inputmask-core';`

I'm using ts-loader in webpack with typescript 2.4.2, and I have the following type roots set up in tsconfig.json:

"typeRoots": [
  "./node_modules/@types",
  "./src/client/types"
]

I tried to mimic the package structure in node_modules/@types:

src/client/types
|--inputmask-core
  |--index.d.ts

With the following in index.d.ts:

declare class InputMask {}
export default InputMask;

But the error is still there. What am I doing wrong? Where should I place those custom .d.ts files?

And what is the difference between node_modules/@types and any other type root? Why does TypeScript treat them differently?

question from:https://stackoverflow.com/questions/45382951/where-should-i-place-custom-d-ts-files

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use paths instead of typeRoots

"typeRoots" is meant for global code. i.e. something that is declared in the global namespace, and you want to include it. For modules, they have their own scope, all you need is path mapping.. something like:

{
    "compilerOptions": {
        "target": "es2017",
        "baseUrl": "./",
        "paths": {
            "*": [ "src/client/@custom_types/*"]
        }
    },
    "exclude": [ "node_modules", "src/client/@custom_types", ... ]
}

Note: baseUrl is required with paths, and you probably also want to add the dir to exclude.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...