7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

TypeScriptのimportはどこに書くことができるか

Posted at

TypeScript HandbookのModuleのところを読んでいたら、こんなコードが出てきた。

内部モジュール

Test.ts
/// <reference path="Validation.ts" />
/// <reference path="LettersOnlyValidator.ts" />
/// <reference path="ZipCodeValidator.ts" />
...
var validators: { [s: string]: Validation.StringValidator; } = {};
validators['ZIP code'] = new Validation.ZipCodeValidator();
validators['Letters only'] = new Validation.LettersOnlyValidator();

外部モジュール

Test.ts
import validation = require('./Validation');
import zip = require('./ZipCodeValidator');
import letters = require('./LettersOnlyValidator');
...
var validators: { [s: string]: validation.StringValidator; } = {};
validators['ZIP code'] = new zip.ZipCodeValidator();
validators['Letters only'] = new letters.LettersOnlyValidator();

内部モジュールの時は、Validation.ZipCodeValidatorだったのが、外部モジュールの時はzip.ZipCodeValidatorとして参照している。わかるんだけどこれどうにかまとめられないのかなと思って考えてみた。

Validation.ts
export interface StringValidator {
    isAcceptable(s: string): boolean;
}
// 以下追記
import zip = require("./ZipCodeValidator");
import letters = require("./LettersOnlyValidator");
export import ZipCodeValidator = zip.ZipCodeValidator;
export import LettersOnlyValidator = letters.LettersOnlyValidator;

importしてからのexport。これならTest.ts側でvalidation.ZipCodeValidatorとして参照できる。

あるいはこうも書けそうだ。

Validation.ts
import zip = require("./ZipCodeValidator");
import letters = require("./LettersOnlyValidator");
module Validator {
    export interface StringValidator {
        isAcceptable(s: string): boolean;
    }
    export import ZipCodeValidator = zip.ZipCodeValidator;
    export import LettersOnlyValidator = letters.LettersOnlyValidator;
}
export = Validator;

外部モジュールのimportはファイルのトップレベルにしか書けないが、Aliasとしてのimportはモジュール内にも書くことができる。

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?