我阅读了TypeScript模块解析的工作原理。

我有以下存储库:@tsstack/di。编译后,目录结构如下:

├── dist
│   ├── annotations.d.ts
│   ├── annotations.js
│   ├── index.d.ts
│   ├── index.js
│   ├── injector.d.ts
│   ├── injector.js
│   ├── profiler.d.ts
│   ├── profiler.js
│   ├── providers.d.ts
│   ├── providers.js
│   ├── util.d.ts
│   └── util.js
├── LICENSE
├── package.json
├── README.md
├── src
│   ├── annotations.ts
│   ├── index.ts
│   ├── injector.ts
│   ├── profiler.ts
│   ├── providers.ts
│   └── util.ts
└── tsconfig.json

在package.json中,我写了“main”:“dist/index.js”。

在Node.js中,一切正常,但TypeScript:

import {Injector} from '@ts-stack/di';

找不到模块“@ts stack/di”的声明文件/path/to/node_modules/@tsstack/di/dist/index.js”隐式具有“any”类型。

然而,如果我按如下方式导入,那么一切都正常:

import {Injector} from '/path/to/node_modules/@ts-stack/di/dist/index.js';

我做错了什么?


当前回答

对我有用的是将依赖项安装为开发依赖项。上述禁用隐式类型检查的解决方案有效,但这使我无法利用严格类型代码。因此,您需要做的就是在所有的@types模块安装中附加--save-dev标志。希望这对你也有用

其他回答

您可能需要创建扩展名为.d.ts的文件。

将此文件名推送到tsconfig.json文件的include键下:

  "include": [
    "src",
    "index.d.ts"
  ]

这应该是工作

这种方式对我有效:

1.在声明文件(例如index.d.ts)中添加自己的声明(可能在项目根目录下)

declare module 'Injector';

2.将index.d.ts添加到tsconfig.json

  {
    "compilerOptions": {
        "strictNullChecks": true,
        "moduleResolution": "node",
        "jsx": "react",
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "allowSyntheticDefaultImports":true,
        "target": "es5",
        "module": "ES2015",
        "declaration": true,
        "outDir": "./lib",
        "noImplicitAny": true,
        "importHelpers": true
      },
      "include": [
        "src/**/*",
        "index.d.ts",   // declaration file path
      ],
      "compileOnSave": false
    }

这就是我工作的方式。

在我的例子中,我使用了一个没有定义类型的库:react mobile datepicker

a.在/src中创建文件夹。在我的例子中,我使用了以下路径:/src/typengs/。

b.创建.dts文件。例如:/src/typerings/react-mobile-datepicker.dts

c.我使用以下代码扩展其财产并使其类型安全:

declare module 'react-mobile-datepicker' {
  class DatePicker extends React.Component<DatePickerProps, any> {}

  interface DatePickerProps {
    isPopup?: boolean;
    theme?: string;
    dateConfig?: DatePickerConfig;
  }

  export interface DatePickerConfig {
    prop1: number;
    pro2: string;
  }
  export default DatePicker;
}

d.按照通常使用第三方库的方式导入类型。

import DatePicker, { DatePickerConfig, DatePickerConfigDate } from 'react-mobile-datepicker';

e.更改tsconfig.json并添加以下代码:

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

链接到我用作来源的文章:

https://templecoding.com/blog/2016/03/31/creating-typescript-typings-for-existing-react-components

https://www.credera.com/insights/typescript-adding-custom-type-definitions-for-existing-libraries

我在angular项目中的uuid模块也遇到了同样的问题。

当然不是为了刺激,但在前一行加上“//@ts-ignore”很快就解决了我的问题。

对我有用的是将依赖项安装为开发依赖项。上述禁用隐式类型检查的解决方案有效,但这使我无法利用严格类型代码。因此,您需要做的就是在所有的@types模块安装中附加--save-dev标志。希望这对你也有用