型推論 とは、TypeScript が文脈から型を自動的に割り出すことで、すべてに注釈を付けなくて済むようにする仕組みです。初期値、return 文、使われ方から推論します。
ts
let x = 10; // inferred: number
let s = "hi"; // inferred: string
const arr = [1, 2]; // inferred: number[]
const obj = { : , : };
型推論 とは、TypeScript が文脈から型を自動的に割り出すことで、すべてに注釈を付けなくて済むようにする仕組みです。初期値、return 文、使われ方から推論します。
let x = 10; // inferred: number
let s = "hi"; // inferred: string
const arr = [1, 2]; // inferred: number[]
const obj = { : , : };
function double(n: number) { return n * 2; } // return inferred as number
[1, 2, 3].map(n => n * 2); // `n` inferred as number from the array — no annotation needed
この 文脈的型付け(contextual typing) こそが、コールバックで引数の注釈がほとんど必要ない理由です。TypeScript は number[] に対する map が number を渡すことを知っています。
let a = "hello"; // widened to string (let can be reassigned)
const b = "hello"; // narrowed to the literal type "hello"
const は変化し得ないため リテラル 型として推論されますが、let は一般的な型へと拡大されます。これはユニオンにおいて重要になります。
const dir = "up"; // type "up"
let dir2 = "up"; // type string
string がほしいとき)。const xs = [] は any[] と推論されるため、number[] と注釈する。推論は、完全に型付けされたまま、TypeScript のコードを JavaScript とほぼ同じくらい簡潔に保ちます。
推論が いつ 働くか(そしていつ型が拡大されるか)を理解すれば、実際に役立つ場所にだけ注釈を付けられるようになります。