Typescript Discriminated Union allows invalid state
I am trying to use a Typescript Discriminated Union to model a rather common scenario when loading data asynchronously:
type LoadingState = { isLoading: true; }
type SuccessState = { isLoading: false; isSuccess: true; }
type ErrorState = { isLoading: false; isSuccess: false; errorMessage: string; }
type State = LoadingState | SuccessState | ErrorState;
According to my understanding, this should limit the allowed combinations of values according to the type definitions. However, the type system is happy to accept the following combination:
const testState: State = {
isLoading: true,
isSuccess: true,
errorMessage: "Error!"
}
I expect an error here. Is there something I am missing or in some way misusing the type definitions?
This is an issue with the way excess property checks work on unions. If an object literal is assigned to a variable of union type, a property will not be marked as excess if it is present on any of the union members. If we don't consider excess properties to be an error (and except for object literals they are not considered an error), the object literal you specified could be an instance of LoadingState
(an instance with isLoading
set to true
as mandated and a couple of excess properties).
To get around this undesired behavior we can add properties to LoadingState
to make your object literal incompatible with LoadingState
type LoadingState = { isLoading: true; isSuccess?: undefined }
type SuccessState = { isLoading: false; isSuccess: true; }
type ErrorState = { isLoading: false; isSuccess: false; errorMessage: string; }
type State = LoadingState | SuccessState | ErrorState;
const testState: State = { // error
isLoading: true,
isSuccess: true,
errorMessage: "Error!"
}
We could even create a type that would ensure such member will be added
type LoadingState = { isLoading: true; }
type SuccessState = { isLoading: false; isSuccess: true; }
type ErrorState = { isLoading: false; isSuccess: false; errorMessage: string; }
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends any ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, undefined>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>
type State = StrictUnion< LoadingState | SuccessState | ErrorState>
const testState: State = { // error
isLoading: true,
isSuccess: true,
errorMessage: "Error!"
}