Mutually exclusive properties
Concept and syntax
Use a union with optional never fields to reject objects containing both alternatives. With exactOptionalPropertyTypes, an optional never property must be absent; without it, explicit undefined may pass. Structural types still allow unrelated extra fields through variables, so this is not a general exact-object validator.
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.
type Choice = {email:string; phone?:never} | {phone:string; email?:never};function show(c:Choice){ return c.email ?? c.phone; }console.log(show({email:"a@b"}),show({phone:"123"}));Expected output:
a@b 123Option comparison: explicit undefined
This separate snippet compiles under the normal settings. Add --exactOptionalPropertyTypes and it is rejected with TS2375. This tests absence versus an explicit undefined value.
type Choice = {email:string; phone?:never} | {phone:string; email?:never};const choice:Choice={email:"a@b",phone:undefined};console.log(choice.email);Common mistake
Intentionally invalid; compile separately and do not execute.
type Choice = {email:string; phone?:never} | {phone:string; email?:never};const both:Choice={email:"a@b",phone:"123"};Expected diagnostic: TS2322. The object supplies two mutually exclusive fields. Keep exactly one.
Practice and recap
Compare explicit undefined with and without exactOptionalPropertyTypes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Mutually exclusive properties — 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 Choice = {email:string; phone?:never} | {phone:string; email?:never};function show(c:Choice){ return c.email ?? c.phone; }console.log(show({email:"a@b"}),show({phone:"123"}));Which diagnostic and explanation match the rejected example under the lesson settings?
type Choice = {email:string; phone?:never} | {phone:string; email?:never};const both:Choice={email:"a@b",phone:"123"};