【问题标题】:What's the correct folder structure for custom typings for this module?此模块的自定义类型的正确文件夹结构是什么?
【发布时间】:2020-01-11 15:47:15
【问题描述】:

我有一个名为@xmpp/client 的模块的自定义类型。我正在尝试将这些添加到我的 TypeScript 项目中,但无法让编译器识别模块的类型。

我在一个名为 types 的文件夹中输入了我的内容,所以我的文件夹结构如下所示:

.
├── app.json
├── App.tsx
├── package.json
├── src
│   └── <snip>
├── types
│   └── @xmpp
│        └── client.d.ts
├── tsconfig.json
└── yarn.lock

我尝试了几种不同的文件夹结构,例如 types/@xmpp/client/index.d.ts 等等,但没有任何效果 - 每次编译时,我都会收到错误 Cannot find module '@xmpp/client'

我的tsconfig.json如下:

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "jsx": "react-native",
    "lib": ["dom", "esnext"],
    "moduleResolution": "node",
    "noEmit": true,
    "skipLibCheck": true,
    "resolveJsonModule": true,
    "strictNullChecks": true,
    "typeRoots": ["./node_modules/@types", "./types"]
  },
  "includes": ["src/**/*.{ts,tsx}", "types/**/*.d.ts"]
}

有人能发现这个设置有什么明显的问题吗?我的tsconfig.json 看起来是否正确,我应该如何为名称中带有斜杠的模块构建我的types 文件夹?

自定义类型如下:

import { EventEmitter } from "react-native";

declare module "@xmpp/client" {
  export function client(options: {
    service?: string;
    domain?: string;
    resource?: string;
    username?: string;
    password?: string;
    credentials?: (
      auth: ({ username: string, password: string }) => any,
      mechanism: string
    ) => any;
  }): XmppClient;

  type XmppClient = EventEmitter & {
    start: () => void;
    stop: () => void;
    send: (...args: any) => Promise<any>;
  };
  export function jid(): any;

  <snip>
}

【问题讨论】:

  • 可以分享types/@xmpp/client.d.ts的内容吗?

标签: typescript typescript-typings


【解决方案1】:

根据this comment from a similar GitHub issue on the TypeScript repo,您需要做的一件事是将您的imports 移动到declare module '@xmpp/client' { ... } 的主体内,如下所示:

declare module '@xmpp/client' {
  import { EventEmitter } from "react-native";
  // ...and so on
}

您还需要在 client 函数中更正 options.credentials 的类型签名。

auth: ({ username: string, password: string }) => any

应该是这样的:

auth: (params: { username: string, password: string }) => any

如果在修复这些问题后问题仍然存在,那么问题可能与您的 tsconfig 有关,但我现在看起来很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多