0
0

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 1 year has passed since last update.

型の定義を外部に宣言する(namespace付き)

Last updated at Posted at 2023-07-18

namespace なし

型の宣言

  • [filename].tsとして宣言する
./src/types/app.ts
// 型の宣言

export type CustomValueType = {
  value0: string;
  value1: number;
  value2: object;
}

export type CustomArgType = {
  arg0: string;
  arg1: number;
  arg2: object;
}

型の参照

./src/app.ts

// 型を import 
import { CustomValueType, CustomArgType } form "./types/app";

//-----------
// 変数の宣言
//-----------

// import した型を使用
const values : CustomValueType = {
  value0: "hoge",
  value1: 10,
  value3: { ... }
}

//-----------
// 関数の宣言
//-----------

/**
* @param {string} arg0
* @param {number} arg1,
* @param {CustomType} arg2
*/
const sampleFunction = (
  arg0: string,
  arg1: number,
  // import した型を使用
  arg2: CustomArgType
) => {
  
  ...

}

namespace あり

型の宣言

  • [filename].tsとして宣言する
./src/types/app.ts
// 型の宣言

export type CustomValueType = {
  value0: string;
  value1: number;
  value2: object;
}

export type CustomArgType = {
  arg0: string;
  arg1: number;
  arg2: object;
}

型の参照

./src/app.ts

// 型 に 名前(= namespace)を付けて import
// ※ AppTypes が namespace
// ※ namespace 自体に命名規則は無い
// ※ ローカルコード内で判別しやすい名前をつける
import * as AppTypes form "./types/app";

//-----------
// 変数の宣言
//-----------

// import した型を使用
const values : AppTypes.CustomValueType = {
  value0: "hoge",
  value1: 10,
  value3: { ... }
}

//-----------
// 関数の宣言
//-----------

/**
* @param {string} arg0
* @param {number} arg1,
* @param {CustomType} arg2
*/
export const sampleFunction = (
  arg0: string,
  arg1: number,
  // 定義した型を使用
  arg2: AppTypes.CustomArgType) => {
  
}

その他

  • パブリックな場で namespace を固定化する/しないの議論は不毛(ローカルルールで十分足りる)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?