> For the complete documentation index, see [llms.txt](https://typescript-jp.gitbook.io/deep-dive/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://typescript-jp.gitbook.io/deep-dive/project/namespaces.md).

# 名前空間

名前空間は、JavaScriptで使用される次の一般的なパターンの便利な構文を提供します。

```ts
(function(something) {

    something.foo = 123;

})(something || (something = {}))
```

基本的に、`something || (something = {})`は、無名関数`function(something) {}`が何かを既存オブジェクト(`something ||`部分)に追加するか、新しいオブジェクト( `|| (something = {})`の部分)を作って何かを追加することを可能にします。これが意味することは、このように何らかの分岐で分割された2つのブロックを持つことができるということです。

```ts
(function(something) {

    something.foo = 123;

})(something || (something = {}))

console.log(something); // {foo:123}

(function(something) {

    something.bar = 456;

})(something || (something = {}))

console.log(something); // {foo:123, bar:456}

```

これは、グローバルな名前空間を汚染しないようにJavaScriptでよく使われます。ファイルベースのモジュールでは、これを心配する必要はありませんが、このパターンは、それでも、一連の関数の論理グループ化(logical grouping)に役立ちます。そのため、TypeScriptは、`namespace`キーワードを使ってグループ化する手段を提供します:

```ts
namespace Utility {
    export function log(msg) {
        console.log(msg);
    }
    export function error(msg) {
        console.error(msg);
    }
}

// usage
Utility.log('Call me');
Utility.error('maybe!');
```

`namespace`キーワードは、先ほど見たのと同じJavaScriptを生成します：

```ts
(function (Utility) {

// Add stuff to Utility

})(Utility || (Utility = {}));
```

注意すべきことは、名前空間を入れ子にすることができるので、`Utility`の下に`Messaging`名前空間を入れ子にするために`namespace Utility.Messaging`のようなことができるということです。

たいていのプロジェクトでは、簡単なデモと古いJavaScriptコードを移植するために、外部モジュールと`namespace`を使用することをオススメします。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://typescript-jp.gitbook.io/deep-dive/project/namespaces.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
