简体   繁体   English

实现此自定义打字稿模块的正确方法是什么?

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

Let's say I want to implement and use the following ts module. 假设我要实现并使用以下ts模块。 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? 另外,从ng2组件中引用和使用此模块的正确方法是什么? 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. 这是来自angular 1.x项目的,但TS或angular的版本无关紧要,因为这是模块之间进行通信的打字稿。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 TypeScript 中实现“toJson”function 的正确方法是什么? - What is the proper way to implement a 'toJson' function in TypeScript? 实现常量的正确方法是什么? - What's the proper way to implement constant variable? 在 Typescript 中使用 ReactDomServer.renderToString 的正确方法是什么 - What's the proper way of using ReactDomServer.renderToString with Typescript 使用变量在 VueJs 中使用 SASS 实现暗模式的正确方法是什么 - what's the proper way to implement darkmode in VueJs with SASS using variables 实现此JSON.parse的正确方法是什么? - what is the proper way to implement this JSON.parse? 在 Firebase 中实施身份验证的正确方法是什么? - What is the proper way to implement authentication in Firebase? 使用 reduce() 函数实现此例程的正确方法是什么? - what is the proper way to implement this routine with reduce() function? 实现Porthole.js根据内容高度调整iframe大小的正确方法是什么? - What's the proper way to implement Porthole.js for resizing an iframe based on content height? 在 javascript 中导入 webassembly 模块的正确方法是什么 - What is the proper way to import webassembly module in javascript 将 ref 传递给 prop 的正确方法是什么? - What's the proper way of passing a ref to a prop?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM