Search code examples
jquerytypescriptsmartadmin

External jQuery Library in typescript file


i am working on an Asp.net MVC project with Smartadmin theme and Typescript with JQuery typings for Dom manipulation, there is a jquery library called SmartMessageBox for prompt messages ,is there an easy way to use this library inside my typescript file because i get Error Build:Property 'SmartMessageBox' does not exist on type 'JQueryStatic'


Solution

  • If the message box is only used in one file, the easiest solution is to add something like this at the top of the file:

    declare const jQuery: JQueryStatic & {
        // *** Choose one of the following ***
        // Most basic:
        SmartMessageBox: any;
        // Better (assuming SmartMessageBox is a function):
        SmartMessageBox(/*param type info*/): /*return type or void*/;
    };
    

    This says jQuery is a global object whose type is the union of the interface JQueryStatic and the interface describing SmartMessageBox.

    If the message box or other "smart admin" types are used in multiple files, you should look into writing a .d.ts file. The official documentation and the default jQuery .d.ts file should be helpful in figuring out what to do. Save the file under <project root>/typings/smart-admin/index.d.ts and add the following in your tsconfig.json:

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

    This tells the compiler to look for type definitions under ./typings as well as ./node_modules/@types (the default location for @types packages installed from npm).