Currently, I am developing an event system within Unity Tiny as the built-in framework's functionality is quite limited. While I have managed to get it up and running, I now aim to enhance its user-friendliness for my team members. In this endeavor, I attempted to employ typeguarding to restrict users from utilizing different types, but unfortunately, I encountered difficulties in making it work effectively. Do you have any suggestions or insights that could help me overcome this challenge?
I have already explored the following resources: - https://medium.com/ovrsea/checking-the-type-of-an-object-in-typescript-the-type-guards-24d98d9119b0 - https://dev.to/krumpet/generic-type-guard-in-typescript-258l
One key challenge I faced is that Unity Tiny utilizes ES5, which restricts access to object.constructor.name for determining the type name. Consequently, leveraging "instanceof" proves to be unfeasible.
Furthermore, attempts such as (object as T) or (object as T).type have not yielded successful outcomes for me.
export class Event<T> implements IEvent<T>{
private handlers: {(data?: T): void}[] = [];
public type : T;
constructor(value: T){
this.type = value;
}
public On(handler: { (data?: T): void }) : void {
this.handlers.push(handler);
}
public Off(handler: { (data?: T): void }) : void {
this.handlers = this.handlers.filter(h => h !== handler);
}
public Trigger(data?: T) {
this.handlers.slice(0).forEach(h => h(data));
}
public Expose() : IEvent<T> {
return this;
}
}
export class EventUtils {
public static events = new Object();
public static CreateEvent<T>(eventEntity: ut.Entity, nameOfEvent: string) : void{
this.events[nameOfEvent] = new game.Event<T>();
}
public static Subscribe<T>(nameOfEvent: string, handeler: {(data? : T): void}) : void{
//Loop through events object, look for nameOfEvent, use checkEventType() to check if it is the same type as given generic, then subscribe if true.
}
public static Trigger<T>(nameOfEvent: string, parameter?: T) : void{
//Loop through events object, look for nameOfEvent, use checkEventType() to check if it is the same type as given generic, then trigger if true.
}
private static checkEventType<T>(object: any) : object is Event<T>{
let temp : T;
let temp2 = {temp};
if (object.type instanceof temp2.constructor.name) {
return true;
}
return false;
}
}
}
private static checkEventType<T>(object: any) : object is Event<T>{
let temp : T;
if (object.type as typeof temp) {
return true;
//always returns true even if the type is different
}
return false;
}
}
Additionally, I encountered issues with:
let temp : T;
if ((object.type as typeof temp).type) {
return true;
//property 'type' does not exist in 'T'
}
return false;