如何添加自定义“类型"在打字稿 2.0/3.0 [英] How to add custom "typings" in typescript 2.0 / 3.0

查看:39
本文介绍了如何添加自定义“类型"在打字稿 2.0/3.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据这篇文章分类系统打字稿 2.0 已更改,因此现在尚不清楚如何附加自定义类型.我应该总是为此创建 NPM 包吗?

According to this article typings system for typescript 2.0 has changed and so it is not clear how to attach custom typings now. Should I always create NPM package for that?

先谢谢你!

推荐答案

您可以为您的项目创建本地自定义类型,您可以在其中声明 JS 库的类型.为此,您需要:

You can create local custom typings just for your project, where you can declare types for JS libraries. For that, you need to:

  1. 创建目录结构来保存您的类型声明文件,使您的目录结构看起来像这样:

  1. Create directory structure to keep your type declaration files so that your directory structure looks similar to this:

 .
 ├── custom_typings
 │   └── some-js-lib
 │       └── index.d.ts
 └── tsconfig.json

  • index.d.ts 文件中,为您的 JS 库添加一个声明:

  • In the index.d.ts file, add a declaration for your JS library:

     declare module 'some-js-lib' {
       export function hello(world: string): void
     }
    

  • (可选:如果您有 TypeScript >= 4.x,则跳过) 在您的 compilerOptions 部分中添加对此类型声明的引用>tsconfig.json:

  • (Optional: skip if you have TypeScript >= 4.x) Add a reference to this type declaration in the compilerOptions section of your tsconfig.json:

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

  • 在代码中使用声明的模块:

  • Use the declared module in your code:

     import { hello } from 'some-js-lib'
    
     hello('world!')
    

  • 这篇关于如何添加自定义“类型"在打字稿 2.0/3.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆