Typescript void

Created By: chatGPT

TypeScript defines the void type to represent the absence of a type. It indicates that a function does not return a value. This is useful for functions that perform an action but do not need to return anything meaningful. Significantly, if a function is declared to return void, it can also return undefined, but it should not return any other value.
function logMessage(message: string): void {
    console.log(message);
}
If you try to return a value other than undefined from a void function, TypeScript will raise a compilation error. This helps to catch potential bugs where a function's return value is mistakenly used.
function incorrectExample(): void {
    return 42; // Error: Type '42' is not assignable to type 'void'.
}
In the context of event handlers or similar functions where no return value is necessary, using void can clarify the intent of the code. It signals that the primary purpose of the function is to carry out a side effect, such as updating the UI or logging information, rather than producing a result.
document.getElementById('myButton')?.addEventListener('click', function(): void {
    alert('Button clicked!');
});
Additionally, when using callbacks or promises, specifying void can help developers understand that a particular function does not return a value. This can aid in writing clearer and more maintainable code, avoiding confusion about return values.
const fetchData = (): Promise<void> => {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('Data fetched!');
            resolve();
        }, 1000);
    });
};
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