TypeScript Explicit Types & Inference
There are two ways a value gets its type in TypeScript:
- Explicit typing – you write the type yourself with an annotation:
let age: number = 30; - Type inference – you leave the annotation out and the compiler works out the type from the value:
let age = 30;
Both produce exactly the same type checking. Knowing when to use each one keeps your code safe and short.
Explicit annotations
An annotation is a colon followed by a type, placed after the variable or parameter name:
let firstName: string = "Mai";
let score: number = 87;
let passed: boolean = score >= 50;
function describe(who: string, points: number): string {
return `${who} scored ${points}`;
}
console.log(describe(firstName, score), passed);Mai scored 87 true
Inference
Drop the annotations and hover over the variables in an editor: TypeScript already knows firstName is a string. The inferred type is enforced just as strictly as an explicit one:
let firstName = "Mai"; // inferred: string
let score = 87; // inferred: number
score = 92; // fine
score = "ninety-two"; // error - score is a numbermain.ts(5,1): error TS2322: Type 'string' is not assignable to type 'number'.
Inference also works for return values, arrays and objects:
function area(width: number, height: number) {
return width * height; // return type inferred as number
}
const sizes = [3, 5, 8]; // number[]
const point = { x: 1, y: 2 }; // { x: number; y: number }
const total = area(sizes[0], point.y);
console.log(total.toFixed(1));
console.log(point.z);main.ts(10,19): error TS2339: Property 'z' does not exist on type '{ x: number; y: number; }'.
The compiler inferred the full shape of point from its literal, so point.z is rejected as a likely typo.
let vs const: literal inference
const variables can never change, so TypeScript infers the narrowest possible type — the literal type of the exact value. let variables get the wider, general type:
let mood = "happy"; // type: string
const planet = "Earth"; // type: "Earth"
mood = "sleepy"; // OK, any string
let target: "Earth" | "Mars" = planet; // OK - planet is exactly "Earth"
console.log(mood, target);sleepy Earth
You'll explore literal types properly in the Literal Types lesson.
When inference isn't enough
If you declare a variable without a value, TypeScript has nothing to infer from. In strict mode you must annotate it, or the compiler complains when it can't work out a type:
let result: string;
const ok = true;
if (ok) {
result = "done";
} else {
result = "failed";
}
console.log(result);done
Function parameters are never inferred from how they're called — they always need an annotation (unless the function is a callback whose type is already known, as in [1, 2].map(n => n * 2)):
function shout(text) {
return text.toUpperCase() + "!";
}
console.log(shout("hi"));main.ts(1,16): error TS7006: Parameter 'text' implicitly has an 'any' type.
Error TS7006 comes from the noImplicitAny rule, part of strict. Without it, text would silently become any and lose all checking. Fix it with function shout(text: string).
Which style should you use?
| Situation | Recommendation |
|---|---|
| Variable initialised with a value | Let TypeScript infer it |
| Variable declared without a value | Annotate it |
| Function parameters | Always annotate |
| Function return types | Optional; annotate exported/public functions to document intent |
Empty arrays [] |
Annotate (const ids: number[] = []) |
| You want a wider type than the value | Annotate (let id: string | number = 1) |
Tip: Over-annotating (
const count: number = 0;) is harmless but noisy. Most TypeScript style guides prefer inference wherever the type is obvious from the value.
Test yourself
What type does TypeScript infer for let total = 0;?
- any
- 0
- number
- unknown
What type does TypeScript infer for const unit = "kg";?
- string
- "kg"
- any
- String
What does error TS7006 "implicitly has an 'any' type" usually mean?
- A variable was used before it was declared
- A function parameter has no type annotation
- A module could not be found
- A number was assigned to a string