简体   繁体   中英

what's the proper way to implement this custom typescript module?

Let's say I want to implement and use the following ts module. It's just a basic validator that validates a first name:

export namespace Validators
{
    export class NameValidator
    {
        constructor()
        {
        }

        FirstNameIsValid(firstName: string)
        {
            return firstName.length < 20;
        }
    }
}

What would be the correct way for me to implement the module above? Also, what would be the correct way for me to reference and use this module from my ng2 component? The following import statement doesn't work:

import { Validators.NameValidator } from './modules/name-validator';

The way I have done it in the past is to create a module

module Formatter{

  export class SsnFormatter {
        ssn: string;
        constructor(unformattedSsn: string) {
            this.ssn = unformattedSsn.replace(/(\d{3})(\d{2})(\d{4})/, '$1-$2-$3');
        }
        formatSsn() {
            return this.ssn;    
        }
    }
}

Then within the other typescript files call it as

let f = new Formatter.SsnFormatter('111111111');
console.log(f);

As long as your class is within the same module namespace you should be able to reference it directly.

This was from an angular 1.x project but the version of TS or angular should not matter this is typescript communicating between modules.

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