Expand on SharedUnionFields
with a type that keeps all the union fields.
This is a simplified version of #386.
This new type will simply change non-shared fields to optional with value unknown
. Or with an option (proposed name exact
), will be changed to be optional with a value of the union of all values for that property within the union.
Edit: This new type will change each field to be optional with a value of the union of all values for that property within the union.
SharedUnionFields
's example (probably not that great an example of why you'd actually want to use this type)import type {AllUnionFields} from 'type-fest';
type Cat = {
name: string;
type: 'cat';
catType: string;
};
type Dog = {
name: string;
type: 'dog';
dogType: string;
};
function displayPetInfo(petInfo: Cat | Dog) {
// typeof petInfo =>
// {
// name: string;
// type: 'cat';
// catType: string;
// } | {
// name: string;
// type: 'dog';
// dogType: string;
// }
console.log('name: ', petInfo.name);
console.log('type: ', petInfo.type);
// TypeScript complains about `catType` and `dogType` not existing on type `Cat | Dog`.
console.log('animal type: ', petInfo.catType ?? petInfo.dogType);
}
function displayPetInfo(petInfo: AllUnionFields<Cat | Dog>) {
// typeof petInfo =>
// {
// name: string;
// type: 'cat' | 'dog';
// catType?: string;
// dogType?: string;
// }
console.log('name: ', petInfo.name);
console.log('type: ', petInfo.type);
// No TypeScript error.
console.log('animal type: ', petInfo.catType ?? petInfo.dogType);
}
No response
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too