Typescript event handling

Created By: chatGPT

In TypeScript, handling events is similar to handling events in JavaScript, but with the added benefit of type checking and interfaces. You can use interface types to define event attributes, which makes the handling of events more robust and predictable.
interface MyEvent extends Event {
    myData: string;
}

const myButton = document.getElementById('myButton');

if (myButton) {
    myButton.addEventListener('click', (event: MyEvent) => {
        console.log('Button clicked!');
        console.log(event.myData); // type checked
    });
}
You can also define custom events. By doing so, you can encapsulate specific data that you want to pass through the event. This is beneficial when you have more complex interactions.
class MyCustomEvent extends Event {
    myData: string;
    constructor(type: string, myData: string) {
        super(type);
        this.myData = myData;
    }
}

const myCustomEvent = new MyCustomEvent('customEvent', 'Hello, World!');
window.dispatchEvent(myCustomEvent);
To listen for custom events, you can use the addEventListener method. Ensure that the event type in the listener matches the custom event type you defined.
window.addEventListener('customEvent', (event: MyCustomEvent) => {
    console.log('Caught custom event!');
    console.log(event.myData); // Hello, World!
});
In a React application using TypeScript, event handling takes a different shape, but the principles remain the same. You define event handlers and attach them to elements with type safety.
import React from 'react';

const MyComponent: React.FC = () => {
    const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {
        console.log('Button clicked!');
    };

    return (
        <button onClick={handleClick}>Click Me</button>
    );
};
Using Event Types from the React library enhances type safety in your applications. For instance, if you're handling form events, you'd use React.FormEvent.
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    console.log('Form submitted!');
};

return (
    <form onSubmit={handleSubmit}>
        <button type="submit">Submit</button>
    </form>
);
Introduction And SetupVariablesData TypesAnyUnknownVoidNeverStringNumberBooleanArrayTupleEnumObjectInterfaceType AliasMethodsFunctionArrow FunctionReturn TypeParametersDefault ParametersOptional ParametersRest ParametersControl FlowIf StatementElse StatementSwitch StatementFor LoopWhile LoopDo While LoopFor...of LoopFor...in LoopBreak StatementContinue StatementFunctionsFunction OverloadingRecursive FunctionExpression FunctionOperatorsArithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsConditional (ternary) OperatorData StructuresArrayTupleObjectMapSetCommentsSingle Line CommentMulti Line CommentSyntaxType AnnotationsType InferenceNamespaceModuleExportImportDecoratorsAmbient DeclarationsEvent HandlingEvent ListenersAddEventListenerRemoveEventListenerError HandlingTry...catch StatementThrow StatementFinally BlockCustom Error TypesAsync AwaitPromisesGenericsConditional TypesMapped TypesIntersection TypesUnion TypesLiteral TypesDiscriminated UnionsType GuardsTypeof GuardInstanceof GuardAssertion FunctionsModule Augmentation