- Notifications
You must be signed in to change notification settings - Fork0
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
License
joshcaughtfire/TypeScript
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This is a fork of Microsoft's TypeScript that adds support forthrows clauses in function signatures, enabling explicit exception type declarations and compile-time validation of error handling.
You can read not-to-serious article about this here:Fork Typescript: You Can Just Do Things
- Explicit exception declarations in function signatures
- Compile-time validation that thrown exceptions match the declared throws clause
- Support for complex types including unions, conditionals, and generics
- Type inference for exception types in function bodies
- IntelliSense integration for better developer experience
// Declare that a function can throw specific error typesfunctionparseNumber(input:string):numberthrowsTypeError,RangeError{if(typeofinput!=='string'){thrownewTypeError('Input must be a string');// ✅ Valid - TypeError is declared}constnum=parseInt(input);if(isNaN(num)){thrownewRangeError('Invalid number format');// ✅ Valid - RangeError is declared}returnnum;}// Or let TypeScript infer the throws clause from the function bodyfunctionparseNumber(input:string)/* throws TypeError, RangeError */{if(typeofinput!=='string'){thrownewTypeError('Input must be a string');// Inferred: TypeError}constnum=parseInt(input);if(isNaN(num)){thrownewRangeError('Invalid number format');// Inferred: RangeError}returnnum;}// and when you call it, TypeScript will check if the function throws the correct error typesfunctiontest(){// ❌ Error: Function does not declare throwsparseNumber('123');}functiontest2()throws{// ✅ Valid - no error, pass through any exceptionsparseNumber('123');}
// Empty throws clause allows rethrowing any caught exceptionsfunctionsafeOperation<T>(fn:()=>T):Tthrows{try{returnfn();}catch(error){// Log error and rethrowconsole.error('Operation failed:',error);throwerror;// ✅ Valid - empty throws clause allows rethrowing}}
// Multiple exception types using union syntaxfunctionprocessData(data:unknown):stringthrowsTypeError|ValidationError{if(typeofdata!=='object'){thrownewTypeError('Data must be an object');// ✅ Valid}if(!isValid(data)){thrownewValidationError('Invalid data format');// ✅ Valid}returnJSON.stringify(data);}
// Conditional exception types based on generic parametersfunctionconvert<Textendsstring|number>(value:T):stringthrowsTextendsstring ?TypeError :RangeError{if(typeofvalue==='string'){if(value.length===0){thrownewTypeError('Empty string not allowed');// ✅ Valid when T extends string}returnvalue;}else{if(value<0){thrownewRangeError('Negative numbers not allowed');// ✅ Valid when T extends number}returnvalue.toString();}}
interfaceDataProcessor{// Method signatures can include throws clausesprocess(data:string):ProcessedDatathrowsValidationError;// Optional throws clause with multiple typesvalidate?(input:unknown):booleanthrowsTypeError,ValidationError;}classMyProcessorimplementsDataProcessor{process(data:string):ProcessedDatathrowsValidationError{if(!data.trim()){thrownewValidationError('Data cannot be empty');// ✅ Valid}return{processed:data.trim()};}}
functionriskyOperation():stringthrowsError{if(Math.random()>0.5){thrownewTypeError('Random failure');// ❌ Error: TypeError not declared in throws clause}thrownewError('Expected failure');// ✅ Valid - Error is declared}// Function without throws clause cannot throwfunctionsafeFunction():string{thrownewError('Oops');// ❌ Error: Function does not declare any exceptions in throws clause}
// TypeScript can infer throws clause from explicit throws in function bodyfunctioninferredThrower(value:unknown)/* throws TypeError | RangeError */{if(typeofvalue!=='number'){thrownewTypeError('Value must be a number');// Inferred: TypeError}if(value<0){thrownewRangeError('Value must be non-negative');// Inferred: RangeError}returnvalue.toString();}// TypeScript infers: function inferredThrower(value: unknown): string throws TypeError | RangeError// Mixed explicit and inferred throwsfunctionmixedThrower(data:string):numberthrowsSyntaxError{if(!data){thrownewTypeError('Data is required');// ❌ Error: TypeError not in explicit throws clause}if(data==='invalid'){thrownewSyntaxError('Invalid data format');// ✅ Valid - SyntaxError is declared}returnparseInt(data);}// Conditional throws inferencefunctionconditionalInference(condition:boolean){if(condition){thrownewError('Condition failed');// Inferred: Error}// TypeScript infers: throws Error (only when condition is true)return'success';}####ArrowFunctionswithThrowsClauses```typescript// Arrow functions support throws clauses tooconstasyncParser=async(input:string):Promise<number>throwsTypeError=>{if(!input){thrownewTypeError('Input is required');// ✅ Valid}returnparseInt(input);};// Generic arrow function with conditional throwsconstconditionalThrower=<T>(value:T):stringthrowsTextendsError ?never :TypeError=>{if(valueinstanceofError){returnvalue.message;// No exception thrown when T extends Error}if(typeofvalue!=='string'){thrownewTypeError('Value must be string or Error');// ✅ Valid when T doesn't extend Error}returnvalue;};
Functionsmust explicitly declare throws clauses to call other functions that throw exceptions:
// ❌ Functions without throws clauses cannot call throwing functionsfunctioncaller(){parseNumber('123');// Error: Function throws but not declared in throws clause}// ✅ Explicit empty throws clause allows any exceptionsfunctioncallerWithEmptyThrows()throws{parseNumber('123');// Valid - can rethrow any exceptions}// ✅ Explicit specific throws clause must be compatiblefunctioncallerWithSpecificThrows()throwsTypeError,RangeError{parseNumber('123');// Valid - throws clause covers TypeError and RangeError}
Note: Throws inference determines a function's signature, but validation requires explicit throws declarations for calling throwing functions.
This fork is based on Microsoft's TypeScript. For the original project, documentation, and community resources, see below:
TypeScript is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at theplayground, and stay up to date viaour blog andTwitter account.
Find others who are using TypeScript atour community page.
For the latest stable version:
npm install -D typescript
For our nightly builds:
npm install -D typescript@next
There are many ways tocontribute to TypeScript.
- Submit bugs and help us verify fixes as they are checked in.
- Review thesource code changes.
- Engage with other TypeScript users and developers onStackOverflow.
- Help each other in theTypeScript Community Discord.
- Join the#typescript discussion on Twitter.
- Contribute bug fixes.
This project has adopted theMicrosoft Open Source Code of Conduct. For more information seetheCode of Conduct FAQ or contactopencode@microsoft.comwith any additional questions or comments.
For details on our planned features and future direction, please refer to ourroadmap.
About
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- TypeScript99.9%
- Other0.1%