Emmanuel Akinfulubi

TypeScriptBasic

Type inference in TypeScript

5 Let inference do the work

easy

Declare several variables with no annotations at all and show what TypeScript worked out for each. Include one case where const and let are inferred differently.

Stuck? Three hints, smallest first
  1. 1. Hover a variable in your editor to see the inferred type. That is the fastest way to check.
  2. 2. const greeting = 'hi' is inferred as the literal type "hi", not as string.
  3. 3. Arrays are inferred from their contents, so a mixed array becomes a union of the element types.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

const greeting = 'hi';        // inferred as the literal type "hi"
let mutableGreeting = 'hi';   // inferred as string, because it can change
const total = 42;             // 42
const ok = true;              // true
const plates = ['LAG-441-XA', 'ABJ-772-KM'];   // string[]
const mixed = [1, 'two', true];                // (string | number | boolean)[]

// Proof that the const version is narrower than the let version:
// mutableGreeting can take any string...
mutableGreeting = 'hello';
// ...but a variable typed "hi" could not.

function describe(value: unknown): string {
  return Array.isArray(value) ? `array of ${value.length}` : typeof value;
}

console.log(describe(greeting), describe(total), describe(ok));
console.log(describe(plates), describe(mixed));

test('literal type still behaves as text', greeting.toUpperCase(), 'HI');
test('let was widened to string', mutableGreeting, 'hello');
test('array inferred and usable', plates.length, 2);
test('mixed array keeps all three', mixed.length, 3);

Output


      

The difference between const greeting = 'hi' and let mutableGreeting = 'hi' is worth holding onto. A const can never change, so TypeScript gives it the narrowest possible type, the literal "hi". A let might change, so it widens to string. That single rule is what makes as const useful later.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.