TypeScript Assertion Functions: Safe at Runtime, Verified at Compile Time

Runtime says 'Safe.' Compiler says 'Error.' But why? 🤔 In JavaScript, it’s common to write functions that throw errors if assumptions aren't met. We call these 'Assertion Functions.' At runtime, they work perfectly. But historically, TypeScript had a blind spot here. Before TS 3.7, even if you validated inputs and threw errors, the compiler didn't 'learn' anything from it. To the type system, these were just 'functions that might throw.' This forced developers into an awkward spot - The code was safe, but we still had to use unsafe type assertions (as string) just to make the compiler happy. Starting with TypeScript 3.7, we got Assertion Signatures (also known as Assertion Functions). An assertion function signals to TypeScript - 'If I return successfully, you can guarantee this value has a specific type.' You use the 'asserts' keyword in the return type. If the function completes, TypeScript permanently narrows the type for the rest of the scope. Remember that Assertion signatures are a power tool. They override TypeScript’s analysis. If your assertion logic is flawed, the compiler will still trust you, potentially leading to runtime crashes that TypeScript won't catch. Use them to bridge the gap between runtime truths and compile-time safety but write them with care. #TypeScript #JavaScript #Programming #Coding #WebDevelopment

  • text

To view or add a comment, sign in

Explore content categories