Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

License

NotificationsYou must be signed in to change notification settings

joshcaughtfire/TypeScript

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

🔥 TypeScript with Throws Clause Support

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

✨ Features

  • 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

📝 Syntax Examples

Basic Exception Declaration

// 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 (Function Can Rethrow)

// 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}}

Union Types in Throws Clauses

// 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);}

Generic Throws Clauses with Conditional Types

// 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();}}

Interface Method Signatures

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()};}}

Type Inference and Validation

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}

Throws Clause Inference from Function Body

// 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;};

🚨 Important: Explicit Throws Declaration Required

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.

🔗 Original TypeScript

This fork is based on Microsoft's TypeScript. For the original project, documentation, and community resources, see below:

CInpm versionDownloadsOpenSSF Scorecard

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.

Installing

For the latest stable version:

npm install -D typescript

For our nightly builds:

npm install -D typescript@next

Contribute

There are many ways tocontribute to TypeScript.

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.

Documentation

Roadmap

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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript99.9%
  • Other0.1%

[8]ページ先頭

©2009-2025 Movatter.jp