【问题标题】:Own @types-style declaration in TypeScript在 TypeScript 中拥有自己的 @types 样式声明
【发布时间】:2017-07-03 08:04:39
【问题描述】:

我想在 browserify/tsify 包中使用 assert 模块。请参阅 https://www.npmjs.com/package/asserthttps://github.com/substack/browserify-handbook#builtinshttps://nodejs.org/api/assert.html。简而言之,它是浏览器中node-js 兼容的assert 模块,即browserify builtin。

所以我将@types/assert 添加到我的package.json。但是声明模块无法识别(似乎有问题)。所以我想做一个等效的node_modules/@types/assert 但在node_modules 之外,因为node_modules 不应该在源代码管理中。

有可能吗?如果没有,我可以/应该使用/// <reference 老式语法或declare module "assert" 还是什么?

【问题讨论】:

  • 你用的是systemjs还是CLI哪个
  • 我不使用 systemjs。我不确定 CLI,但似乎我将 browserify 的内置加载器用于 CommonJS 模块。

标签: typescript typescript-typings typescript2.0


【解决方案1】:

澄清@Bruno Grieder 的答案。

tsc 如何查找.d.ts 文件在https://www.typescriptlang.org/docs/handbook/module-resolution.html 中进行了说明

declare module 'assert'的机制称为环境模块:

https://www.typescriptlang.org/docs/handbook/modules.html#ambient-modules

【讨论】:

    【解决方案2】:

    乍一看,声明模块看起来不错(没有彻底的测试),但无论如何,假设你在谈论this library

    创建一个typings/assert/assert.d.ts 目录/子目录/文件,它将受源代码控制

    assert.d.ts 必须构造为外部模块定义,它导出单个符号 assert。内容几乎是在@types/assert 中找到的内容的直接副本(带有您提到的所需更正)

    declare module 'assert' {
    
        function assert(value:any, message?:string):void;
    
        namespace assert {
    
             export function fail(actual?:any, expected?:any, message?:string, operator?:string):void;
    
             ...
    
        }
    
        export = assert
    
    }
    

    tsconfig.json 中,只需确保typings 目录的内容包含(即不排除)编译。

    【讨论】:

    • 澄清了我的问题。不是power-assert,但您的建议仍然适用
    • 这可以解释模块声明“似乎有问题”,因为从 @types/assert 加载的定义清楚地提到它们是为 power-assert 设计的
    • npmjs.com/package/@types/assert 明确表示“此包包含断言和电源断言的类型定义”
    • 该方法适用于 tsc,但不适用于 Visual Studio。 @types/ 两者都工作过
    猜你喜欢
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-12-30
    • 2018-06-16
    • 2011-06-09
    • 2017-02-08
    • 2021-07-20
    相关资源
    最近更新 更多