← Fundamentals
Fundamentals

Inference, coercion, and conversion

How is a type inferred, and when is a value converted?

Follow operand types and conversion boundaries before trusting a calculation.

Outcome

Predict the type each language infers, tell an implicit coercion from an explicit conversion, and choose conversions that keep fractions, signs and cents.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Type inference
The checker working out a type the code did not write, from the value or the use.
Coercion
A conversion the language makes on its own, without a conversion in the code.
Conversion
Code that turns a value of one type into another, such as Number(text), float64(n) or as f64.
Truncation
Dropping the fraction of a number, rounding toward zero.
Unsigned
An integer type whose representable values are nonnegative. Out-of-range arithmetic handling depends on the language, operation and checked or wrapping mode.

Choosing a type and converting a value

Type inference chooses a type from an expression and its context when no annotation is written. That chosen type still governs the operations that follow. Converting a result afterward is a different step from converting an operand before the operation.

Coercion is a conversion the language applies implicitly; an explicit conversion is one the program requests. Neither name establishes that information is preserved. Inspect the source and destination types, the supported range and the operation’s treatment of fractions, signs and failed text conversion.

01Inferred types

An inferred type decides how the arithmetic is done

A film club averages runtimes, counts down to screenings and totals ticket sales. Each calculation passes through types nobody wrote: an inferred integer, a string read from a cue sheet, a price that becomes cents. Each language decides differently when a value is converted and what is lost.

Before summarizing the film programme, reduce the average to 7 total minutes across 2 short films. total and films have no written type: predict their quotient.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const total = 7;
const films = 2;

console.log(total / films);
What is printed?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts

Use the selected native command. The C++ track uses 32-bit int and unsigned; the Rust command selects edition 2024 so TryFrom is in the prelude.

02Implicit conversions

Some languages convert on their own, and some refuse

The screening tools also accept textual fields, unsigned countdown data or bounded seat counts. These reduced probes test what the language converts before the calculation or comparison. Predict the selected native result.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const seats: string = "5";

console.log(seats + 2, Number(seats) + 2);
What is printed?

03Explicit conversions

An explicit conversion still has to decide what to do with a value that does not fit

A report needs a deliberate conversion, but writing a conversion does not specify every failure or boundary policy. Inspect the shown text and numeric conversions before using the same tools for ticket amounts.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
console.log(Number(""), Number("1e3"), Number("12 min"), parseInt("12 min"));
What is printed?

04Repair the film club

Runtimes, the cue sheet, then ticket totals

The film-club toolkit needs a runtime summary for programme planning, cue-sheet status for screenings, and a ticket-sales report for reconciliation. Repair the complete native utility supplied for each job.

Each file contains its imports, reader and complete caller.

Repair the film club

Summarize numeric runtimes, interpret cue-sheet times, then convert and display signed ticket totals.

  1. easy · F-CONV-V4-1 Summarize the runtimes
  2. medium · F-CONV-V4-2 Read the cue sheet
  3. hard · F-CONV-V4-3 Total the ticket sales
In the frontend Convert a runtime field before adding the trailer minutes. Optional

A schedule form passes runtime text to a preview that adds a five-minute trailer. The preview must interpret that field as a number before addition; string concatenation would display a different duration. Empty or non-finite input gets a prompt instead of a numeric preview.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export default function RuntimePreview({ minutesText }: { minutesText: string }) {
  const minutes = Number(minutesText);

  if (minutesText.trim() === "" || !Number.isFinite(minutes)) {
    return <p>Enter runtime minutes</p>;
  }

  return <p>With trailer: {minutes + 5} minutes</p>;
}

Each render computes from current props. Number is an explicit conversion; the empty-text check matters because Number of empty text is zero. This preview does not validate the film-club import’s full range or format.

Sources: ECMAScript: Number conversion,React: keeping components pure,Svelte: $derived.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.