简体   繁体   中英

How to create a Typescript declaration file for a custom class without require/import/export

Hoping someone can help get my head around typescript declaration files and how to access my custom-made classes.

So let's imagine I have a custom class to display an alert message as an example:

CustomAlert.ts:

/// <reference path="typings/CustomAlert.d.ts" />
module MdlCustomAlerts{    
    class CustomAlert{
        constructor(alertMessage:string, alertOptions:IAlertOptions){
            alert(message);
        }
    }
}

CustomAlert.d.ts

declare module MdlCustomAlerts{
    interface IAlertOptions{

    }

    class CustomAlert{
      constructor(alertMessage:string, alertOptions:IAlertOptions)
    }
}

app.ts

/// <reference path="typings/MyAlert.d.ts" />

var alert1 = new MdlCustomAlerts.CustomAlert("Hello World", {});

First of all, I get an 'duplicate identifier' error in CustomAlert.ts as class CustomAlert is defined in the definitions. I need a way of accessing my CustomAlert by using the definitions without the use of import/require (we don't use require.js so this causes issues).

I think I need to do something like export a public identifier for the class (perhaps renaming the class in the definitions to customAlert and then exporting the reference) but I can't seem to make any way work. If someone could help me get to the solution I'd be very grateful!

Thanks in advance

You can reference typescript fies directly from other typescript files; you do not need type definitions for them.

Type definitions are meant to type javascript files for use from Typescript.

... and you should use modules (ES6/commonJS - not what is now called namespaces). Failure to do so, as your application will get bigger, you will fall into nightmarish problems of ordering your TS files to get proper compilation.

CustomAlert.ts

export class CustomAlert{
  constructor(alertMessage:string, alertOptions:IAlertOptions){
    alert(message);
  }
}

app.ts

import {CustomAlert} from './CustomAlert'

var alert1 = new CustomAlert("Hello World", {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM