Hi everyone
I implemented a type guard for types that contain the type property. I use this property to identify objects such as:
type UserSignIn = { type: 'user-sign-in' };
type UserSignOut = { type: 'user-sign-out' };
type UserAction = UserSignIn | UserSignOut
I then write predicate functions that infer the object properties:
export const isUserSignIn = (action: UserAction) => isTypedOf<UserSignIn>(action, 'user-sign-in');
Here's how I've defined the type guard function:
/**
* An object that contains a property named 'type'. This property uniquely identifies a type among
* other types that also contain the same property.
*/
type TypedObject = { type: string };
/**
* Type guard for objects that represent their types via the `type` property.
*
* @param value - the object being type guarded
* @param type - the name of the type that matches the object
*/
export function isTypedOf<T extends TypedObject>(value: TypedObject, type: string): value is T {
return value.type === type;
}
Everything works great at runtime, but it's a painful writing the predication functions because the IDE doesn't suggest me the value of the type.
Can someone help me rewrite the type guard function so that the IDE is able to infer the possible type value and suggest it?
Thank you,
Freitas