This piece of code effectively enforces the conditional requirement for the isDirty
field to be included in a lecture object:
- If the
id
is a string, then anisDirty
field must be added to the object: - If the
id
is a number, then the object cannot have anisDirty
field.
type LectureT = LectureIdT & {
title: string;
};
/**
* If `id` is a string, Lecture must have an `isDirty` field. If `id` is a number, there should be no `isDirty` field.
*/
type LectureIdT =
| { id: string; isDirty: boolean }
| { id: number; isDirty?: never };
const lectureMockWithNumberId: LectureT = {
id: 1,
title: 'Lecture 1',
// isDirty: false, // Uncomment to see error
};
const lectureMockWithStringId: LectureT = {
id: "1",
title: 'Lecture 2',
isDirty: false,
};
You can experiment with this code on the following TS Playground.
The Question: Why is the question mark necessary in isDirty?: never
?
My Findings:
After removing the question mark from isDirty?: never
to make it isDirty: never
, the code stops functioning as expected:
type LectureIdT =
| { id: string; isDirty: boolean }
| { id: number; isDirty: never };
An error in TypeScript appears for lectureMockWithNumberId
:
Type '{ id: number; title: string; }' is not assignable to type 'LectureT'.
Type '{ id: number; title: string; }' is not assignable to type '{ id: number; isDirty: never; } & { title: string; }'.
Property 'isDirty' is missing in type '{ id: number; title: string; }' but required in type '{ id: number; isDirty: never; }'.
The error message indicates that isDirty
is required, which seems incorrect since its type is
never</code - meaning it should never be required, right?</p>
<p>I am puzzled by why adding the question mark makes it work. It feels counterintuitive.</p>
<p>To make sense of it, I tried changing it to <code>isDirty: never | undefined
:
type LectureIdT =
| { id: string; isDirty: boolean }
| { id: number; isDirty: never | undefined };
To my surprise, the error persists! Doesn't the ?
in something like a?: string
equate to a: string | undefined
?
This confusion arises from:
- ...the necessity of the question mark
?
inisDirty?: never
and the supposed impossibility ofisDirty: never;
. - ...the different behavior exhibited by
?
when used alongsidenever
.