Array covariance
Concept and syntax
A mutable array of a narrower object type can be assigned to an array of a wider type. Writing a wider element through that alias can violate assumptions of the original array. Use readonly arrays for read-only consumers and copy or validate when accepting mutation.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
The accepted example deliberately exposes a static-safety limitation. Do not imitate the unsafe path in production.
type Base={id:number};type Full={id:number;label:string};const full:Full[]=[{id:1,label:"tea"}];const wide:Base[]=full;wide.push({id:2});console.log(full[1].label===undefined);Expected output:
truefull and wide refer to the same array. After wide.push, the second element has no label at runtime even though the original Full[] annotation says it does. The true output exposes the discrepancy.
Common mistake
Intentionally invalid; compile separately and do not execute.
type Base={id:number};const values:readonly Base[]=[{id:1}];values.push({id:2});Expected diagnostic: TS2339. The readonly contract exposes no push. Use a new mutable copy if mutation is required.
Practice and recap
Replace the wide alias with readonly Base[] and try the push again.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array covariance — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Base={id:number};type Full={id:number;label:string};const full:Full[]=[{id:1,label:"tea"}];const wide:Base[]=full;wide.push({id:2});console.log(full[1].label===undefined);Which diagnostic and explanation match the rejected example under the lesson settings?
type Base={id:number};const values:readonly Base[]=[{id:1}];values.push({id:2});