1
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?

TypeScriptのdeclareを使ってエディタを騙す

1
Posted at

TypeScriptのdeclareを使っていろいろできることを紹介する試みです。

declareを使ったアンビエント宣言とは

declareとはTypeScriptのキーワードの一つで、実装を伴わない変数の定義のためのものです。

untyped.js
export let bar = baz();//文字列が出てくる関数
export function foo(hikisu){
return `得点は${hikisu}です。`
}
types.d.ts
declare let bar: string;
declare function foo(hikisu: number):string

これは主にJavaScript製のライブラリを型定義する際に使うためのものです。
これが普通の使い方です。

別な使い方

実装を伴わないということで存在しない関数を作りだすのに使われることがあります。

このライブラリはTypeScriptの型から自動でバリデートを作ってくれます。その際に型を比較する関数が型定義にのみ存在しています。

エディタを騙そう

エディタは実体がないのに補完の候補として出してくれるみたい。
declareとbabel(トランスフォーマのプラグイン)を使うとこのような簡易的なプリプロセッサマクロを作ることもできます。

macro.d.ts
declare const macro = 1234567890;
usemacro.ts
foo(macro);
console.log(macro + 810);

変換後

usemacro.js
foo(1234567890);
console.log(1234567890 + 810);

ちゃんと補完も出てくれる。
image.png

結論

混乱を招くので変な使い方は避けましょう。

1
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
1
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?