56. TypeScript classes
Module 12 · approximately 20 minutes
Open Interactive LessonDiscover and predict
What does typescript classes let the compiler check, and what still needs a runtime test?
Understand
A class exists at runtime and can also describe instance types. Fields and methods implement behavior; annotations document and check their contracts. Definite initialization is checked under strict settings. A class is not required for every data shape: a plain interface plus functions is often enough. Compare the emitted class with erased annotations to see which parts survive.
Important source operations
- Line 1:
class Counter { value=0; increment():void { this.value+=1; } } - Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: Counter: Counter; value: number; increment: () => void.
- Line 2:
const counter=new Counter();counter.increment(); - Follow the value relationship and inspect compiler information at this source position. Actual checker declaration information: counter: Counter.
- Line 3:
console.log(counter.value); - Observe the actual runtime value. A log is evidence for this input, not proof of every permitted value.
Working concept in practice
A class exists at runtime and can also describe instance types. Fields and methods implement behavior; annotations document and check their contracts. Definite initialization is checked under strict settings. A class is not required for every data shape: a plain interface plus functions is often enough. Compare the emitted class with erased annotations to see which parts survive.
main.ts
class Counter { value=0; increment():void { this.value+=1; } }
const counter=new Counter();counter.increment();
console.log(counter.value);Exact authored reference result
{
"diagnostics": [],
"logs": [
"1"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Investigate the compiler or runtime fault
Predict the result of the supplied wrong operation. Read actual compiler feedback; if it compiles, investigate the real runtime mismatch instead. Fault: counter.value="one";
main.ts
class Counter { value=0; increment():void { this.value+=1; } }
const counter=new Counter();counter.value="one";
console.log(counter.value);Exact authored reference result
{
"diagnostics": [
{
"code": 2322,
"category": "Error",
"message": "Type 'string' is not assignable to type 'number'.",
"file": "main.ts",
"line": 2,
"column": 29,
"start": 91,
"length": 13
}
],
"logs": [],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
A compiler-clean behavioral counterexample
A numeric boundary, count or index changes while remaining a number. Compare the actual output with the independent expected result. This intentionally incorrect program demonstrates why runtime tests remain necessary.
main.ts
class Counter { value=1; increment():void { this.value+=1; } }
const counter=new Counter();counter.increment();
console.log(counter.value);Exact authored reference result
{
"diagnostics": [],
"logs": [
"2"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
An executable behavior contract
Capture the actual observable result and assert the independently authored expected output. This optional professional test pattern introduces helper/rest/async syntax; focus on the primary example first if those concepts are new.
main.ts
const __observed:string[]=[];
function __capture(...values:unknown[]):void{__observed.push(values.map(value=>typeof value==="string"?value:typeof value==="undefined"?"undefined":typeof value==="number"&&!Number.isFinite(value)?String(value):JSON.stringify(value)??String(value)).join(" "));}
class Counter { value=0; increment():void { this.value+=1; } }
const counter=new Counter();counter.increment();
__capture(counter.value);
async function verifyContract():Promise<void>{await new Promise<void>(resolve=>setTimeout(resolve,15));const expected:string[]=["1"];if(JSON.stringify(__observed)!==JSON.stringify(expected))throw new Error("Behavior contract failed");console.log("Contract verified");}
verifyContract().catch(error=>console.log(error instanceof Error?error.message:String(error)));Exact authored reference result
{
"diagnostics": [],
"logs": [
"Contract verified"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Transfer to another useful feature
Apply the topic in a different small task. Predict the output and identify the type/runtime boundary before editing.
main.ts
class Label { constructor(public text:string){} upper():string{return this.text.toUpperCase();}}
console.log(new Label("ready").upper());Exact authored reference result
{
"diagnostics": [],
"logs": [
"READY"
],
"error": null
}Recorded reference evidence; the interactive lab recompiles your current source for actual diagnostics.
Build and test
Repair the supplied source so it compiles under the lesson settings and produces 1. Equivalent implementations may pass the observable contract.
Hint 1
Read the first meaningful diagnostic and its source location, or compare the first runtime mismatch when the program compiles.
Hint 2
The exercise changes counter.increment(); to counter.value="one";. Determine whether the contract, caller or business operation is wrong.
Hint 3
Restore counter.increment(); or implement an equivalent correct contract. Do not hide the issue with any or an unjustified assertion; run the stated behavior check.
Explain, reflect and extend
Explain which evidence came from the compiler and which came from execution. Give a second input and a predicted result. What assumption could still fail outside this example?
Extend the useful feature with a boundary case and one invalid external input. Write the expected behavior first, then verify it using actual diagnostics and tests.
Troubleshooting
Verify the active filename, first diagnostic, actual inferred/flow type and emitted output. A type error blocks emission in this lab; an empty runtime pane is not a fabricated success. Browser examples require the DOM preview, while worker execution has no document. Project imports must refer to supplied relative files. Check runtime validation and logical operators when clean compilation still produces the wrong result.