I've run into a problem while working with a TypeScript function that uses conditional types based on an enum.
The enum in question:
export enum FactoryResult {
INTERNAL_FORMALITY_CREATED_WITH_DOCS,
INTERNAL_FORMALITY_INVALID_DOCS,
INTERNAL_FORMALITY_MISSING_DOCS,
}
This is how the function starts:
public fromData<T extends FactoryResult>(
data: FormalityCreationDTO,
filesAttachments: FileAttachment[],
): {
factoryResult: T;
formality: T extends FactoryResult.INTERNAL_FORMALITY_MISSING_DOCS ? never : formality;
invalidDocuments: T extends FactoryResult.INTERNAL_FORMALITY_MISSING_DOCS ? never : FileAttachment[];
} {
if (filesAttachments.length < NumberOfFilesRequiredForCreation.TEST) {
return {
factoryResult: FactoryResult.INTERNAL_FORMALITY_MISSING_DOCS, // <= error
};
...
}}
In this function, I'm using conditional types to define the types of inpiFormality
and invalidDocuments
based on the value of T
. If T
matches a specific key in the FactoryResult
enum, then both properties should be of type never, indicating that they may not be returned.
The issue arises with the first condition in the function:
TS2322: Type 'FactoryResult.INTERNAL_FORMALITY_MISSING_DOCS' is not assignable to type 'T'. 'FactoryResult.INTERNAL_FORMALITY_MISSING_DOCS' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'FactoryResult'.
I would appreciate any assistance in understanding why this error occurs. Thank you for your help!