For example:
type Example = {
'x': string,
'y': null,
};
type Test<T extends keyof Example> = {
prop: Example[T],
};
const test1: Test<'x'> = { prop: 'x' }; // success
const test2: Test<'y'> = { prop: null }; // success
const test3: Test<'z'> = {}; // Property 'prop' is missing in type '{}' but required in type 'Test<"z">'.
In this scenario, I want the prop
property to be optional when its value is null
. Essentially, I would like { prop: null }
and {}
to have the same meaning.
In my practical application, I am dealing with API handlers that may return different data fields based on conditions. If a field is unnecessary, I prefer to exclude it rather than defining it as null
.
One potential solution is:
type Test<T extends keyof Example> = Example[T] extends null
? { prop?: null }
: { prop: Example[T] };
However, if many fields need to be optional, this conditional statement can grow quite lengthy. Is there a more efficient approach?