【问题标题】:call alertifyjs from typescripts从打字稿调用 alertify js
【发布时间】:2016-07-26 06:52:56
【问题描述】:

我正在尝试将一些 js 代码迁移到 typescript。 具体来说,我在使用 AlertifyJs 时遇到了麻烦。现在 Alertify 似乎有很多东西。

  1. discontinued project by fabien-d
  2. 拿起并继续 alertifyjs dot org
  3. MohammadYounes alertifyjs dot com 收录

现在我可以在 distinctlyTyped 上找到 (1) 的 d.ts,但其他的则找不到。 我想用(3)!

我想以某种方式包装或直接从 ts 调用 alertify.confirm("you go", "girl");

我怎样才能做到这一点?

谢谢

PS:在 vs2015 中编码

编辑: 以为我会为你漂亮的书呆子提供一个我得到的东西的代码 sn-p

///<reference path="../typings/jquery/jquery.d.ts"/>
///<reference path="../typings/toastr/toastr.d.ts"/>

module mymodule.Web {
export class CommonTools {

    constructor() {
        toastr.options.closeButton = false;
    }

    showInfo(title: string, message: string) {
        toastr.info(message, title);
    }
    showConfirm(title: string, message: string) {
     //**code goes here**
    }
}
}

【问题讨论】:

    标签: typescript alertifyjs


    【解决方案1】:

    最简单(也是最不安全或优雅)的解决方案可能是将其添加到您的打字稿的全局范围内。

    declare var alertify: any;
    

    这样,typescript 会知道alertify 变量。

    如果你更精确,你可以引入你自己的(例如)AlertifyJSStatic 接口以及你想使用的那些方法,并将其作为alertify 变量的类型。

    interface AlertifyJSStatic {
      confirm(a: string, b:string);
    }
    
    declare var alertify: AlertifyJSStatic;
    

    有时,快速添加自己的需求比迷失在d.ts 库(和版本)中更容易。

    【讨论】:

    • 效果很好,非常感谢。清晰、简洁和简单的答案。我现在想买啤酒!
    【解决方案2】:

    *我看到有一个可接受的答案,但这是我的解决方案。

    对于我的 Angular 项目,在使用 npm 安装后,在 TS 文件的导入部分中,复制以下内容...

    import * as alertifyJs from 'alertifyjs';
    

    从那里开始,使用就是你想要的。

    alertifyJs.confirm('alertify is working');
    

    希望这会有所帮助。干杯

    【讨论】:

      【解决方案3】:

      如果你有一个全局安装的库,像这样声明它

      declare global {
        interface Window {
          alertify: {
            success: Function;
            [key: string]: Function; // for all others
          };
        }
      }
      

      现在可以放心使用

      window.alertify.success(...)
      

      【讨论】:

        【解决方案4】:

        根据Zoltán Tamási 的回答,我创建了一个界面,帮助我解决了我在 TypeScript 中的编译错误:

        // globals/alertify.type.js
        
        interface AlertifyJsStatic {
            alert (title: any, message: any, onok?: string);
            confirm (title: any, message: any, onok?: any, oncancel?: any);
            prompt (title: any, message: any, value?: string, onok?: any, oncancel?: any);
            notify (message: string, type?: string, wait?: number, callback?: any);
        }
        
        declare var alertify: AlertifyJsStatic;
        

        我通过Triple-Slash directive 引用它

        /// <reference path="globals/alertify.type.ts" />
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-13
          • 1970-01-01
          • 2017-11-23
          • 1970-01-01
          • 1970-01-01
          • 2021-09-10
          • 2018-12-07
          • 1970-01-01
          相关资源
          最近更新 更多