Jump to content

TypeScript: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
m Added 5.5 Beta to the table of releases. The beta tag can be removed later when it is properly released.
 
(34 intermediate revisions by 25 users not shown)
Line 22: Line 22:
| implementations =
| implementations =
| dialects =
| dialects =
| influenced by = [[C Sharp (programming language)|C#]], [[Java (programming language)|Java]], [[JavaScript]], [[ActionScript]]<ref>{{Cite web |last=Nelson |first=Gary |date=28 April 2020 |title=How ActionScript foreshadowed TypeScript |url=https://javascript.plainenglish.io/how-actionscript-foreshadowed-typescript-149cdb764de9 |access-date=9 July 2022 |website=Medium |language=en}}</ref>
| influenced by = [[C Sharp (programming language)|C#]], [[F Sharp (programming language)|F#]],<ref>{{cite web |title=The Early History of F# |url=https://fsharp.org/history/hopl-final/hopl-fsharp.pdf |quote=TypeScript was directly influenced by F#: one of the originators of TypeScript was Luke Hoban, who began TypeScript (then called Strada) immediately after working on F# 2.0. Recently he noted the influence of F# on early parts of the TypeScript design [Hoban 2017].}}</ref> [[Java (programming language)|Java]], [[JavaScript]], [[ActionScript]]<ref>{{Cite web |last=Nelson |first=Gary |date=28 April 2020 |title=How ActionScript foreshadowed TypeScript |url=https://javascript.plainenglish.io/how-actionscript-foreshadowed-typescript-149cdb764de9 |access-date=9 July 2022 |website=Medium |language=en}}</ref>
| influenced = [[AtScript]], [[AssemblyScript]]
| influenced = [[AtScript]], [[AssemblyScript]], [[ArkTS]]
| programming language =
| programming language =
| platform =
| platform =
Line 32: Line 32:
| wikibooks =
| wikibooks =
}}
}}
'''TypeScript''' is a [[free and open-source]] [[high-level programming language|high-level]] [[programming language]] developed by [[Microsoft]] that adds [[static typing]] with optional type [[annotation]]s to [[JavaScript]]. It is designed for the development of large applications and [[source-to-source compiler|transpiles]] to JavaScript.<ref>{{cite web |last=Bright |first=Peter |date=3 October 2012 |title=Microsoft TypeScript: the JavaScript we need, or a solution looking for a problem? |url=https://arstechnica.com/information-technology/2012/10/microsoft-typescript-the-javascript-we-need-or-a-solution-looking-for-a-problem/ |url-status=live |access-date=26 April 2015 |work=[[Ars Technica]] |publisher=[[Condé Nast]]}}</ref> Because TypeScript is a [[superset]] of JavaScript, all JavaScript programs are [[syntax (programming languages)|syntactically]] valid TypeScript, but they can fail to [[Type_system#Type_checking|type-check]] for [[type safety|safety]] reasons.
'''TypeScript''' is a [[free and open-source]] [[high-level programming language|high-level]] [[programming language]] developed by [[Microsoft]] that adds [[static typing]] with optional type [[annotation]]s to [[JavaScript]]. It is designed for the development of large applications and [[source-to-source compiler|transpiles]] to JavaScript.<ref>{{cite web |last=Bright |first=Peter |date=3 October 2012 |title=Microsoft TypeScript: the JavaScript we need, or a solution looking for a problem? |url=https://arstechnica.com/information-technology/2012/10/microsoft-typescript-the-javascript-we-need-or-a-solution-looking-for-a-problem/ |access-date=26 April 2015 |work=[[Ars Technica]] |publisher=[[Condé Nast]]}}</ref> Because TypeScript is a [[superset]] of JavaScript, all JavaScript programs are [[syntax (programming languages)|syntactically]] valid TypeScript, but they can fail to [[Type_system#Type_checking|type-check]] for [[type safety|safety]] reasons.


TypeScript may be used to develop JavaScript applications for both [[client-side]] and [[server-side]] execution (as with [[Node.js]] or [[Deno (software)|Deno]]). Multiple options are available for [[transpilation]]. The default TypeScript Compiler can be used,<ref>{{Cite web|url=https://code.visualstudio.com/docs/languages/typescript|title=TypeScript Programming with Visual Studio Code|website=code.visualstudio.com|language=en|access-date=12 February 2019}}</ref> or the [[Babel (transcompiler)|Babel]] compiler can be invoked to convert TypeScript to JavaScript.
TypeScript may be used to develop JavaScript applications for both [[client-side]] and [[server-side]] execution (as with [[Node.js]], [[Deno (software)|Deno]] or [[Bun (software)|Bun]]). Multiple options are available for transpilation. The default TypeScript Compiler can be used,<ref>{{Cite web|url=https://code.visualstudio.com/docs/languages/typescript|title=TypeScript Programming with Visual Studio Code|website=code.visualstudio.com|language=en|access-date=12 February 2019}}</ref> or the [[Babel (transcompiler)|Babel]] compiler can be invoked to convert TypeScript to JavaScript.


TypeScript supports definition files that can contain type information of existing JavaScript [[Library (computing)|libraries]], much like [[C++]] [[header files]] can describe the structure of existing [[object file]]s. This enables other programs to use the values defined in the files as if they were statically typed TypeScript entities. There are third-party header files for popular libraries such as [[jQuery]], [[MongoDB]], and [[D3.js]]. TypeScript headers for the [[Node.js]] library modules are also available, allowing development of Node.js programs within TypeScript.<ref>{{cite web |url = https://github.com/borisyankov/DefinitelyTyped |title = borisyankov/DefinitelyTyped |work = [[GitHub]] |access-date = 26 April 2015 }}</ref>
TypeScript supports definition files that can contain type information of existing JavaScript [[Library (computing)|libraries]], much like [[C++]] [[header files]] can describe the structure of existing [[object file]]s. This enables other programs to use the values defined in the files as if they were statically typed TypeScript entities. There are third-party header files for popular libraries such as [[jQuery]], [[MongoDB]], and [[D3.js]]. TypeScript headers for the [[Node.js]] library modules are also available, allowing development of Node.js programs within TypeScript.<ref>{{cite web |url = https://github.com/borisyankov/DefinitelyTyped |title = borisyankov/DefinitelyTyped |work = [[GitHub]] |access-date = 26 April 2015 }}</ref>
Line 43: Line 43:
TypeScript was released to the public in October 2012, with version 0.8, after two years of internal development at Microsoft.<ref>{{cite web |url = http://www.infoworld.com/d/application-development/microsoft-augments-javascript-large-scale-development-203737 |title = Microsoft augments JavaScript for large-scale development |date = 1 October 2012 |work = [[InfoWorld]] |publisher = [[International Data Group|IDG]] |access-date = 26 April 2015 }}</ref><ref>{{cite web |url = https://devblogs.microsoft.com/typescript/announcing-typescript-1-0/ |title = Announcing TypeScript 1.0 |date = 2 April 2014 |first = Jonathan |last = Turner |publisher = Microsoft |work = TypeScript Language team blog |access-date = 20 October 2021 }}</ref> Soon after the initial public release, [[Miguel de Icaza]] praised the language itself, but criticized the lack of mature IDE support apart from [[Microsoft Visual Studio]], which was not available on [[Linux]] and [[MacOS|OS X]] at that time.<ref>{{cite web |url = http://tirania.org/blog/archive/2012/Oct-01.html |title = TypeScript: First Impressions |date = 1 October 2012 |author = Miguel de Icaza |author-link = Miguel de Icaza |quote = ''But TypeScript only delivers half of the value in using a strongly typed language to Unix developers: strong typing. Intellisense, code completion and refactoring are tools that are only available to Visual Studio Professional users on Windows. There is no Eclipse, MonoDevelop or Emacs support for any of the language features'' |access-date = 12 October 2012 }}</ref><ref>{{cite web |url = http://www.zdnet.com/microsoft-typescript-can-the-father-of-c-save-us-from-the-tyranny-of-javascript-7000005054/ |title = Microsoft TypeScript: Can the father of C# save us from the tyranny of JavaScript? |date = 1 October 2012 |publisher = [[ZDNet]] |quote = ''And I think this is a pretty big misstep. If you're building web apps that run on anything other than Windows, you're likely using a Mac and most likely not using Visual Studio. You need the Visual Studio plug-in to get the IntelliSense. All you get without Visual Studio is the strong-typing. You don't get the productivity benefits you get from IntelliSense.''. |access-date = 12 October 2012 }}</ref> As of April 2021 there is support in other IDEs and text editors, including [[Emacs]], [[Vim (text editor)|Vim]], [[JetBrains#WebStorm|WebStorm]], [[Atom (text editor)|Atom]]<ref>{{cite web |url = https://github.com/TypeStrong/atom-typescript |title = TypeStrong: The only TypeScript package you will ever need |website = [[GitHub]] |access-date = 21 July 2016}}</ref> and Microsoft's own [[Visual Studio Code]].<ref>{{cite web |url = http://www.drdobbs.com/windows/working-with-typescript-in-visual-studio/240154792 |title = Working with TypeScript in Visual Studio 2012 |date = 14 May 2013 |work = [[Dr. Dobb's Journal]] |first = Gastón |last = Hillar |access-date = 26 April 2015 }}</ref> TypeScript 0.9, released in 2013, added support for [[Generic programming|generics]].<ref>{{cite web |url = https://www.theregister.co.uk/2013/06/18/typescript_update_0_9/ |title = TypeScript 0.9 arrives with new compiler, support for generics |date = 18 June 2013 |work = [[The Register]] |access-date = 26 April 2015 }}</ref>
TypeScript was released to the public in October 2012, with version 0.8, after two years of internal development at Microsoft.<ref>{{cite web |url = http://www.infoworld.com/d/application-development/microsoft-augments-javascript-large-scale-development-203737 |title = Microsoft augments JavaScript for large-scale development |date = 1 October 2012 |work = [[InfoWorld]] |publisher = [[International Data Group|IDG]] |access-date = 26 April 2015 }}</ref><ref>{{cite web |url = https://devblogs.microsoft.com/typescript/announcing-typescript-1-0/ |title = Announcing TypeScript 1.0 |date = 2 April 2014 |first = Jonathan |last = Turner |publisher = Microsoft |work = TypeScript Language team blog |access-date = 20 October 2021 }}</ref> Soon after the initial public release, [[Miguel de Icaza]] praised the language itself, but criticized the lack of mature IDE support apart from [[Microsoft Visual Studio]], which was not available on [[Linux]] and [[MacOS|OS X]] at that time.<ref>{{cite web |url = http://tirania.org/blog/archive/2012/Oct-01.html |title = TypeScript: First Impressions |date = 1 October 2012 |author = Miguel de Icaza |author-link = Miguel de Icaza |quote = ''But TypeScript only delivers half of the value in using a strongly typed language to Unix developers: strong typing. Intellisense, code completion and refactoring are tools that are only available to Visual Studio Professional users on Windows. There is no Eclipse, MonoDevelop or Emacs support for any of the language features'' |access-date = 12 October 2012 }}</ref><ref>{{cite web |url = http://www.zdnet.com/microsoft-typescript-can-the-father-of-c-save-us-from-the-tyranny-of-javascript-7000005054/ |title = Microsoft TypeScript: Can the father of C# save us from the tyranny of JavaScript? |date = 1 October 2012 |publisher = [[ZDNet]] |quote = ''And I think this is a pretty big misstep. If you're building web apps that run on anything other than Windows, you're likely using a Mac and most likely not using Visual Studio. You need the Visual Studio plug-in to get the IntelliSense. All you get without Visual Studio is the strong-typing. You don't get the productivity benefits you get from IntelliSense.''. |access-date = 12 October 2012 }}</ref> As of April 2021 there is support in other IDEs and text editors, including [[Emacs]], [[Vim (text editor)|Vim]], [[JetBrains#WebStorm|WebStorm]], [[Atom (text editor)|Atom]]<ref>{{cite web |url = https://github.com/TypeStrong/atom-typescript |title = TypeStrong: The only TypeScript package you will ever need |website = [[GitHub]] |access-date = 21 July 2016}}</ref> and Microsoft's own [[Visual Studio Code]].<ref>{{cite web |url = http://www.drdobbs.com/windows/working-with-typescript-in-visual-studio/240154792 |title = Working with TypeScript in Visual Studio 2012 |date = 14 May 2013 |work = [[Dr. Dobb's Journal]] |first = Gastón |last = Hillar |access-date = 26 April 2015 }}</ref> TypeScript 0.9, released in 2013, added support for [[Generic programming|generics]].<ref>{{cite web |url = https://www.theregister.co.uk/2013/06/18/typescript_update_0_9/ |title = TypeScript 0.9 arrives with new compiler, support for generics |date = 18 June 2013 |work = [[The Register]] |access-date = 26 April 2015 }}</ref>


TypeScript 1.0 was released at Microsoft's [[Build (developer conference)|Build]] developer conference in 2014.<ref>{{cite web |url = http://channel9.msdn.com/Events/Build/2014/3-576 |title = TypeScript |first = Anders |last = Hejlsberg |author-link = Anders Hejlsberg |date = 2 April 2014 |publisher = Microsoft |work = [[Channel 9 (Microsoft)|Channel 9]] |access-date = 26 April 2015 }}</ref> [[Visual Studio 2013]] Update 2 provides built-in support for TypeScript.<ref>{{cite web |url = http://www.pcworld.com/article/2101920/microsoft-typescript-graduates-to-visual-studio.html |title = Microsoft TypeScript graduates to Visual Studio |first = Joab |last = Jackson |date = 25 February 2014 |work = [[PC World]] |publisher = [[International Data Group|IDG]] |access-date = 26 April 2015 }}</ref> Further improvement were made in July 2014, when the development team announced a new TypeScript compiler, asserted to have a five-fold performance increase. Simultaneously, the source code, which was initially hosted on [[CodePlex]], was moved to [[GitHub]].<ref>{{cite web |url = http://blogs.msdn.com/b/typescript/archive/2014/07/21/new-compiler-and-moving-to-github.aspx |title = New Compiler and Moving to GitHub |date = 21 July 2014 |publisher = Microsoft |work = TypeScript Language team blog |first = Jonathan |last = Turner |access-date = 26 April 2015 }}</ref>
TypeScript 1.0 was released at Microsoft's [[Build (developer conference)|Build]] developer conference in 2014.<ref>{{cite web |url = http://channel9.msdn.com/Events/Build/2014/3-576 |title = TypeScript |first = Anders |last = Hejlsberg |author-link = Anders Hejlsberg |date = 2 April 2014 |publisher = Microsoft |work = [[Channel 9 (Microsoft)|Channel 9]] |access-date = 26 April 2015 }}</ref> [[Visual Studio 2013]] Update 2 provides built-in support for TypeScript.<ref>{{cite web |url = http://www.pcworld.com/article/2101920/microsoft-typescript-graduates-to-visual-studio.html |title = Microsoft TypeScript graduates to Visual Studio |first = Joab |last = Jackson |date = 25 February 2014 |work = [[PC World]] |publisher = [[International Data Group|IDG]] |access-date = 26 April 2015 }}</ref> Further improvement were made in July 2014, when the development team announced a new TypeScript compiler, asserted to have a five-fold performance increase. Simultaneously, the source code, which was initially hosted on [[CodePlex]], was moved to [[GitHub]].<ref>{{cite web |url = http://blogs.msdn.com/b/typescript/archive/2014/07/21/new-compiler-and-moving-to-github.aspx |title = New Compiler and Moving to GitHub |date = 21 July 2014 |publisher = Microsoft |work = TypeScript Language team blog |first = Jonathan |last = Turner |access-date = 26 April 2015 }}{{dead link|date=August 2023|fix-attempted=yes}}</ref>


On 22 September 2016, TypeScript 2.0 was released, introducing several features, including the ability for programmers to optionally enforce [[null safety]],<ref>{{cite web|first=Peter|last=Bright|url=https://arstechnica.com/information-technology/2016/09/typescript-microsofts-javascript-for-big-applications-reaches-version-2-0/|title=TypeScript, Microsoft's JavaScript for big applications, reaches version 2.0|work=[[Ars Technica]]|publisher=[[Condé Nast]]|date=22 September 2016|access-date=22 September 2016}}</ref> to mitigate what's sometimes referred to as the [[Null pointer#History|billion-dollar mistake]].
On 22 September 2016, TypeScript 2.0 was released, introducing several features, including the ability for programmers to optionally enforce [[null safety]],<ref>{{cite web|first=Peter|last=Bright|url=https://arstechnica.com/information-technology/2016/09/typescript-microsofts-javascript-for-big-applications-reaches-version-2-0/|title=TypeScript, Microsoft's JavaScript for big applications, reaches version 2.0|work=[[Ars Technica]]|publisher=[[Condé Nast]]|date=22 September 2016|access-date=22 September 2016}}</ref> to mitigate what's sometimes referred to as the [[Null pointer#History|billion-dollar mistake]].
Line 74: Line 74:
* [[Tuple]]s
* [[Tuple]]s
* [[Async/await]]
* [[Async/await]]
* Explicit Resource Management<ref>{{Cite web |title=Documentation - TypeScript 5.2 |url=https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html |access-date=2023-11-09 |website=www.typescriptlang.org |language=en}}</ref>


The following features are backported from ECMAScript 2015:
The following features are backported from ECMAScript 2015:
Line 84: Line 85:


=== Compatibility with JavaScript ===
=== Compatibility with JavaScript ===
{{Main|JavaScript}}
TypeScript is a strict superset of [[ECMAScript]] 2015, which is itself a superset of ECMAScript 5, commonly referred to as JavaScript.<ref>{{Cite web |url = https://angular.io/docs/ts/latest/guide/upgrade.html |title = Angular 2 |website = angular.io |access-date = 4 May 2016 }}</ref> As such, a JavaScript program is also a valid TypeScript program and a TypeScript program can seamlessly consume JavaScript. By default the compiler targets ECMAScript 5, the current prevailing standard, but is also able to generate constructs used in ECMAScript 3 or 2015.
TypeScript is a strict superset of [[ECMAScript]] 2015, which is itself a superset of ECMAScript 5, commonly referred to as JavaScript.<ref>{{Cite web |url = https://angular.io/docs/ts/latest/guide/upgrade.html |title = Angular 2 |website = angular.io |access-date = 4 May 2016 }}</ref> As such, a JavaScript program is also a valid TypeScript program and a TypeScript program can seamlessly consume JavaScript. By default the compiler targets ECMAScript 5, the current prevailing standard, but is also able to generate constructs used in ECMAScript 3 or 2015.


With TypeScript, it is possible to use existing JavaScript code, incorporate popular JavaScript libraries, and call TypeScript-generated code from other JavaScript. [http://www.excellentwebworld.com/typescript-vs-javascript Comparison of TypeScript and JavaScript], which is better for building web apps and pages. <ref name="typescript-home-page">{{cite web |url = http://www.typescriptlang.org/ |title = Welcome to TypeScript |work = typescriptlang.org |publisher = [[Microsoft]] |access-date = 26 April 2015 }}</ref> Type declarations for these libraries are provided with the source code.
With TypeScript, it is possible to use existing JavaScript code, incorporate popular JavaScript libraries, and call TypeScript-generated code from other JavaScript.<ref name="typescript-home-page">{{cite web |url = http://www.typescriptlang.org/ |title = Welcome to TypeScript |work = typescriptlang.org |publisher = [[Microsoft]] |access-date = 26 April 2015 }}</ref> Type declarations for these libraries are provided with the source code.


=== Type annotations ===
=== Type annotations ===
Line 96: Line 98:
</syntaxhighlight>
</syntaxhighlight>


Primitive types are annotated using the types <code>number</code>, <code>boolean</code>, and <code>string</code>. These types are distinct from their class counterparts (<code>Number</code>, <code>Boolean</code>, etc), which cannot have operations performed from values directly. For instance, a <code>Number</code> and a <code>number</code> cannot be added. There is additionally <code>undefined</code> and <code>null</code> types for their respective values.
The annotations for the primitive types are <code>number</code>, <code>boolean</code> and <code>string</code>.
Typescript also supports data types with following annotations <code>Array</code>, <code>Enums</code>, <code>void</code>.


Additional data types are: <code>Tuple</code>, <code>Union</code>, <code>never</code> and <code>any</code>.
All other types are annotated using their class name rather than primitives, such as <code>Error</code>. Arrays can be written in two different ways which are both syntactically the same: the generic-based syntax <code>Array<T></code> and a shorthand with <code>T[]</code>.

An array with predefined data types at each index is <code>Tuple</code> type.
A variable that holds more than one type of data is <code>Union</code> type.
Additional built-in data types are tuples, unions, <code>never</code> and <code>any</code>:

When you are sure that something is never going to occur you use <code>never</code> type.
* An array with predefined data types at each index is a tuple, represented as <code>[type1, type2, ..., typeN]</code>.
Weakly- or dynamically-typed structures are of <code>any</code> type.<ref name="TypeScript Language Specification">{{cite web|title=TypeScript: Documentation - Everyday Types|url=https://www.typescriptlang.org/docs/handbook/2/everyday-types.html|access-date=30 March 2021|website=www.typescriptlang.org/}}</ref>
* A variable that can hold more than one type of data is a union, represented using the logical OR <code>|</code> symbol (<code>string | number</code>).
* The <code>never</code> type is used when a given type should be impossible to create, which is useful for filtering mapped types.
* A value of type <code>any</code> supports the same operations as a value in JavaScript and minimal static type checking is performed,<ref>{{Cite web |title=TypeScript Language Specification p.24 |url=http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf |url-status=dead |archiveurl=https://web.archive.org/web/20131117065339/http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf |archivedate=17 November 2013}}</ref> which makes it suitable for weakly or dynamically-typed structures, although this is generally discouraged practice.<ref name="TypeScript Language Specification">{{cite web|title=TypeScript: Documentation - Everyday Types|url=https://www.typescriptlang.org/docs/handbook/2/everyday-types.html|access-date=30 March 2021|website=www.typescriptlang.org/}}</ref>


Type annotations can be exported to a separate ''declarations file'' to make type information available for TypeScript scripts using types already compiled into JavaScript. Annotations can be declared for an existing JavaScript library, as has been done for [[Node.js]] and [[jQuery]].
Type annotations can be exported to a separate ''declarations file'' to make type information available for TypeScript scripts using types already compiled into JavaScript. Annotations can be declared for an existing JavaScript library, as has been done for [[Node.js]] and [[jQuery]].


The TypeScript compiler makes use of [[type inference]] to infer types when types are not given. For example, the <code>add</code> method in the code above would be inferred as returning a <code>number</code> even if no return type annotation had been provided. This is based on the static types of <code>left</code> and <code>right</code> being <code>numbers</code>, and the compiler's knowledge that the result of adding two <code>numbers</code> is always a <code>number</code>. However, explicitly declaring the return type allows the compiler to verify correctness.
The TypeScript compiler makes use of [[type inference]] to infer types when types are not given. For example, the <code>add</code> method in the code above would be inferred as returning a <code>number</code> even if no return type annotation had been provided. This is based on the static types of <code>left</code> and <code>right</code> being <code>numbers</code>, and the compiler's knowledge that the result of adding two <code>number</code>s is always a <code>number</code>. However, explicitly declaring the return type allows the compiler to verify correctness.


If no type can be inferred because of lack of declarations (such as in a JavaScript module without types), then it defaults to the dynamic <code>any</code> type. Additional module types can be provided using a .d.ts declaration file using the <code>declare module "moduleName"</code> syntax.
If no type can be inferred because of lack of declarations, then it defaults to the dynamic <code>any</code> type. A value of the <code>any</code> type supports the same operations as a value in JavaScript and minimal static type checking is performed for operations on <code>any</code> values.<ref>{{Cite web|url=http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf|archiveurl=https://web.archive.org/web/20131117065339/http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf|url-status=dead|title=TypeScript Language Specification p.24|archivedate=17 November 2013}}</ref>


==== Declaration files ====
==== Declaration files ====
When a TypeScript script gets compiled there is an option to generate a ''declaration file'' (with the extension <code>.d.ts</code>) that functions as an [[interface (computing)|interface]] to the [[Component-oriented programming|component]]s in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.
When a TypeScript script gets compiled there is an option to generate a ''declaration file'' (with the extension <code>.d.ts</code>) that functions as an [[interface (computing)|interface]] to the [[Component-oriented programming|component]]s in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.


The concept of declaration files is analogous to the concept of [[header file]] found in [[C/C++]].
The concept of declaration files is analogous to the concept of [[header file|header files]] found in [[C/C++]].
<syntaxhighlight lang="typescript">
<syntaxhighlight lang="typescript">
declare namespace arithmetics {
declare namespace Arithmetics {
add(left: number, right: number): number;
add(left: number, right: number): number;
subtract(left: number, right: number): number;
subtract(left: number, right: number): number;
Line 128: Line 132:
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in [https://github.com/DefinitelyTyped/DefinitelyTyped DefinitelyTyped].
Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in [https://github.com/DefinitelyTyped/DefinitelyTyped DefinitelyTyped].


=== Generics ===
{{Main|Generic programming}}

TypeScript supports [[generic programming]] using a syntax similar to [[Java (programming language)|Java]].<ref>{{cite web |last=Turner |first=Jonathan |date=18 June 2013 |title=Announcing TypeScript 0.9 |url=http://blogs.msdn.com/b/typescript/archive/2013/06/18/announcing-typescript-0-9.aspx |work=TypeScript Language team blog |publisher=[[Microsoft]]}}</ref> The following is an example of the [[identity function]].<ref>{{cite web |title=Generics in Typescript |url=https://www.typescriptlang.org/docs/handbook/generics.html#working-with-generic-type-variables |publisher=[[Microsoft]]}}</ref>

<syntaxhighlight lang="typescript">
function id<T>(x: T): T {
return x;
}
</syntaxhighlight>
=== Classes ===
=== Classes ===
TypeScript uses the same annotation style for class methods and fields as for functions and variables respectively. Compared with vanilla JavaScript classes, a TypeScript class can also implement an interface through the <code>implements</code> keyword, use generic parameters similarly to [[Java (programming language)|Java]], and specify public and private fields.
TypeScript supports ECMAScript 2015 classes that integrate the optional type annotations support.
<syntaxhighlight lang="typescript">
<syntaxhighlight lang="typescript">
class Person {
class Person {
Line 143: Line 157:


toString(): string {
toString(): string {
return `${this.name} (${this.age}) (${this.salary})`; // As of version 1.4
return `${this.name} (${this.age}) (${this.salary})`;
}
}
}
}
</syntaxhighlight>
</syntaxhighlight>


=== Generics ===
TypeScript supports [[generic programming]].<ref>{{cite web |url = http://blogs.msdn.com/b/typescript/archive/2013/06/18/announcing-typescript-0-9.aspx |title = Announcing TypeScript 0.9 |work = TypeScript Language team blog |publisher = [[Microsoft]] |date = 18 June 2013 |first = Jonathan |last = Turner }}</ref> The following is an example of the [[identity function]].<ref>{{cite web|url=https://www.typescriptlang.org/docs/handbook/generics.html#working-with-generic-type-variables|title=Generics in Typescript |publisher=[[Microsoft]]}}</ref>

<syntaxhighlight lang="typescript">
function id<T>(x: T): T {
return x;
}
</syntaxhighlight>
=== Union types ===
=== Union types ===
{{excerpt|Union type|TypeScript}}
{{excerpt|Union type|TypeScript}}
Line 162: Line 168:
{{excerpt|Enumerated type|TypeScript|subsections=yes}}
{{excerpt|Enumerated type|TypeScript|subsections=yes}}
=== Modules and namespaces ===
=== Modules and namespaces ===
TypeScript distinguishes between modules and namespaces. Both features in TypeScript support encapsulation of classes, interfaces, functions and variables into containers. Namespaces (formerly internal modules) utilize [[immediately-invoked function expression]] of JavaScript to encapsulate code, whereas modules (formerly external modules) leverage JavaScript library patterns to do so ([[Asynchronous module definition|AMD]] or [[CommonJS]]).<ref>{{cite web |url = http://blog.oio.de/2014/01/31/an-introduction-to-typescript-module-system/ |title = An introduction to TypeScript's module system |publisher = blog.oio.de |date = 31 January 2014 |author = Sönke Sothmann |access-date = 21 February 2014 |archive-date = 1 February 2014 |archive-url = https://web.archive.org/web/20140201102512/http://blog.oio.de/2014/01/31/an-introduction-to-typescript-module-system/ |url-status = dead }}</ref>
TypeScript distinguishes between modules and namespaces. Both features in TypeScript support encapsulation of classes, interfaces, functions and variables into containers. Namespaces (formerly internal modules) utilize JavaScript [[immediately-invoked function expression|immediately-invoked function expressions]] to encapsulate code, whereas modules (formerly external modules) leverage JavaScript library patterns to do so ([[Asynchronous module definition|AMD]] or [[CommonJS]]).<ref>{{cite web |url = http://blog.oio.de/2014/01/31/an-introduction-to-typescript-module-system/ |title = An introduction to TypeScript's module system |publisher = blog.oio.de |date = 31 January 2014 |author = Sönke Sothmann |access-date = 21 February 2014 |archive-date = 1 February 2014 |archive-url = https://web.archive.org/web/20140201102512/http://blog.oio.de/2014/01/31/an-introduction-to-typescript-module-system/ |url-status = dead }}</ref>


== Development tools ==
== Development tools ==
Line 168: Line 174:
The TypeScript compiler, named <code>tsc</code>, is [[Self-hosting (compilers)|written in TypeScript]]. As a result, it can be compiled into regular JavaScript and can then be executed in any JavaScript engine (e.g. a browser). The compiler package comes bundled with a script host that can execute the compiler. It is also available as a [[Node.js]] package that uses Node.js as a host.
The TypeScript compiler, named <code>tsc</code>, is [[Self-hosting (compilers)|written in TypeScript]]. As a result, it can be compiled into regular JavaScript and can then be executed in any JavaScript engine (e.g. a browser). The compiler package comes bundled with a script host that can execute the compiler. It is also available as a [[Node.js]] package that uses Node.js as a host.


The compiler can "target" a particular edition of ECMAScript (such as [[ECMAScript version history|ES5]] for legacy browser compatibility), but by default compiles to the latest version.
The current version of the compiler supports ECMAScript 5 by default. An option is allowed to target ECMAScript 2015 to make use of language features exclusive to that version (e.g. generators). Classes, despite being part of the ECMAScript 2015 standard, are available in both modes.


=== IDE and editor support ===
=== IDE and editor support ===
* [[Microsoft]] provides a [[Plug-in (computing)|plug-in]] for [[Visual Studio|Visual Studio 2012]] and [[Microsoft WebMatrix|WebMatrix]], full integrated support in [[Visual Studio|Visual Studio 2013]], [[Visual Studio|Visual Studio 2015]], and basic text editor support for [[Emacs]] and [[Vim (text editor)|Vim]].<ref name="blogs.msdn.com">{{cite web |author = Olivier Bloch |title = Sublime Text, Vi, Emacs: TypeScript enabled! |url = http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled.aspx |publisher = [[Microsoft]] |date = 1 October 2012 |access-date = 28 October 2012 }}</ref>
* [[Microsoft]] provides a [[Plug-in (computing)|plug-in]] for [[Visual Studio|Visual Studio 2012]] and [[Microsoft WebMatrix|WebMatrix]], full integrated support in [[Visual Studio|Visual Studio 2013]], [[Visual Studio|Visual Studio 2015]], and basic text editor support for [[Emacs]] and [[Vim (text editor)|Vim]].<ref name="blogs.msdn.com">{{cite web |author = Olivier Bloch |title = Sublime Text, Vi, Emacs: TypeScript enabled! |url = http://blogs.msdn.com/b/interoperability/archive/2012/10/01/sublime-text-vi-emacs-typescript-enabled.aspx |publisher = [[Microsoft]] |date = 1 October 2012 |access-date = 28 October 2012 }}</ref>
* [[Visual Studio Code]] is a (mostly) open-source, cross-platform source code editor developed by Microsoft based on [[Electron (software framework)|Electron]]. It supports TypeScript in addition to several other languages, and offers features like debugging and [[intelligent code completion]].
* [[Visual Studio Code]] supports TypeScript in addition to several other languages, and offers features like debugging and intelligent [[code completion]].
* alm.tools is an open source cloud IDE for TypeScript built using TypeScript, ReactJS and TypeStyle.
* alm.tools is an open source cloud IDE for TypeScript built using TypeScript, ReactJS and TypeStyle.
* [[JetBrains]] supports TypeScript with code completion, refactoring and debugging in its IDEs built on IntelliJ platform, such as [[PhpStorm]] 6, [[WebStorm]] 6, and [[IntelliJ IDEA]],<ref>{{cite web |title = TypeScript support in WebStorm 6 |url = http://blog.jetbrains.com/webide/2013/02/typescript-support-in-webstorm-6 |publisher = JetBrains }}</ref> as well as their Visual Studio Add-in and extension, ReSharper 8.1.<ref>{{cite web |title = TypeScript support in ReSharper 8.1 |date = 28 October 2013 |url = http://blog.jetbrains.com/dotnet/2013/10/28/typescript-support-resharper-81/ |publisher = JetBrains }}</ref><ref>{{Cite web|url=https://www.jetbrains.com/resharper/|title=ReSharper: The Visual Studio Extension for .NET Developers by JetBrains|website=JetBrains}}</ref>
* [[JetBrains]] supports TypeScript with code completion, refactoring and debugging in its IDEs built on IntelliJ platform, such as [[PhpStorm]] 6, [[WebStorm]] 6, and [[IntelliJ IDEA]],<ref>{{cite web |title = TypeScript support in WebStorm 6 |url = http://blog.jetbrains.com/webide/2013/02/typescript-support-in-webstorm-6 |publisher = JetBrains }}</ref> as well as their Visual Studio Add-in and extension, ReSharper 8.1.<ref>{{cite web |title = TypeScript support in ReSharper 8.1 |date = 28 October 2013 |url = http://blog.jetbrains.com/dotnet/2013/10/28/typescript-support-resharper-81/ |publisher = JetBrains }}</ref><ref>{{Cite web|url=https://www.jetbrains.com/resharper/|title=ReSharper: The Visual Studio Extension for .NET Developers by JetBrains|website=JetBrains}}</ref>
Line 186: Line 192:


=== Integration with build automation tools ===
=== Integration with build automation tools ===
{{Main|Build automation}}
Using [[Plug-in (computing)|plug-ins]], TypeScript can be integrated with [[build automation]] tools, including Grunt (grunt-ts<ref>{{cite web |url = https://github.com/basarat/grunt-ts |title = TypeStrong/grunt-ts |work = GitHub |access-date = 26 April 2015 }}</ref>), [[Apache Maven]] (TypeScript Maven Plugin<ref>{{cite web |url = https://github.com/ppedregal/typescript-maven-plugin |title = ppedregal/typescript-maven-plugin |work = GitHub |access-date = 26 April 2015 }}</ref>), Gulp (gulp-typescript<ref>{{cite web |url = https://github.com/ivogabe/gulp-typescript |title = ivogabe/gulp-typescript |work = GitHub |access-date = 14 July 2017 }}</ref>) and [[Gradle]] (TypeScript Gradle Plugin<ref>{{cite web |url = https://github.com/sothmann/typescript-gradle-plugin |title = sothmann/typescript-gradle-plugin |work = GitHub |access-date = 26 April 2015 }}</ref>).
Using [[Plug-in (computing)|plug-ins]], TypeScript can be integrated with [[build automation]] tools, including Grunt (grunt-ts<ref>{{cite web |url = https://github.com/basarat/grunt-ts |title = TypeStrong/grunt-ts |work = GitHub |access-date = 26 April 2015 }}</ref>), [[Apache Maven]] (TypeScript Maven Plugin<ref>{{cite web |url = https://github.com/ppedregal/typescript-maven-plugin |title = ppedregal/typescript-maven-plugin |work = GitHub |access-date = 26 April 2015 }}</ref>), Gulp (gulp-typescript<ref>{{cite web |url = https://github.com/ivogabe/gulp-typescript |title = ivogabe/gulp-typescript |work = GitHub |access-date = 14 July 2017 }}</ref>) and [[Gradle]] (TypeScript Gradle Plugin<ref>{{cite web |url = https://github.com/sothmann/typescript-gradle-plugin |title = sothmann/typescript-gradle-plugin |work = GitHub |access-date = 26 April 2015 }}</ref>).


=== Linting tools ===
=== Linting tools ===
TSLint<ref>{{Cite web|url=https://palantir.github.io/tslint/|title=TSLint|website=palantir.github.io}}</ref> scans TypeScript code for conformance to a set of standards and guidelines. [[ESLint]], a standard JavaScript linter, also provided some support for TypeScript via community plugins. However, ESLint's inability to leverage TypeScript's language services precluded certain forms of semantic linting and program-wide analysis.<ref>{{Cite web|url=https://medium.com/palantir/tslint-in-2019-1a144c2317a9|title=TSLint in 2019|last=Palantir|date=19 February 2019|website=Medium|access-date=24 April 2019}}</ref> In early 2019, the TSLint team announced the linter's deprecation in favor of <code>typescript-eslint</code>, a joint effort of the TSLint, ESLint and TypeScript teams to consolidate linting under the ESLint umbrella for improved performance, community unity and developer accessibility.<ref>{{Cite web|url=https://www.infoq.com/news/2019/02/tslint-deprecated-eslint|title=TSLint Deprecated to Focus Support on typescript-eslint|website=InfoQ|access-date=24 April 2019}}</ref>
TSLint<ref>{{Cite web|url=https://palantir.github.io/tslint/|title=TSLint|website=palantir.github.io}}</ref> scans TypeScript code for conformance to a set of standards and guidelines. [[ESLint]], a standard JavaScript linter, also provided some support for TypeScript via community plugins. However, ESLint's inability to leverage TypeScript's language services precluded certain forms of semantic linting and program-wide analysis.<ref>{{Cite web|url=https://medium.com/palantir/tslint-in-2019-1a144c2317a9|title=TSLint in 2019|last=Palantir|date=19 February 2019|website=Medium|access-date=24 April 2019}}</ref> In early 2019, the TSLint team announced the linter's deprecation in favor of <code>typescript-eslint</code>, a joint effort of the TSLint, ESLint and TypeScript teams to consolidate linting under the ESLint umbrella for improved performance, community unity and developer accessibility.<ref>{{Cite web|url=https://www.infoq.com/news/2019/02/tslint-deprecated-eslint|title=TSLint Deprecated to Focus Support on typescript-eslint|website=InfoQ|access-date=24 April 2019}}</ref>

=== CodeDOM Provider===
CodeDOM<ref>{{Cite web|url=https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/using-the-codedom|title=CodeDOM|website=learn.microsoft.com}}</ref> provides types that represent common types of source code elements, which will be transformed to data types, classes and statements etc. of a programming language through a CodeDOMProvider.<ref>{{Cite web|url=https://learn.microsoft.com/en-us/dotnet/api/system.codedom.compiler.codedomprovider|title=CodeDOMProvider|website=learn.microsoft.com}}</ref> Programmers use CodeDOM and a CodeDOM provider to construct a code generator that generates codes for an application domain.
TypeScript CodeDOM Provider<ref>{{Cite web|url=https://github.com/zijianhuang/TypeScriptCodeDOM|title=TypeScript CodeDOM Provider|website=github.com}}</ref> generates TypeScript codes according to a CodeDOM.


== Release history ==
== Release history ==
Line 269: Line 280:
| 2.7
| 2.7
| {{start date|df=yes|2018|01|31}}
| {{start date|df=yes|2018|01|31}}
| constant-named properties, fixed length tuples
| constant-named properties, fixed-length tuples
|-
|-
| 2.8
| 2.8
Line 277: Line 288:
| 2.9
| 2.9
| {{start date|df=yes|2018|05|14}}
| {{start date|df=yes|2018|05|14}}
| support for symbols and numeric literals in keyof and mapped object types
| support for symbols and numeric literals in <code>keyof</code> and mapped object types
|-
|-
| 3.0
| 3.0
Line 289: Line 300:
| 3.2
| 3.2
| {{start date|df=yes|2018|11|30}}
| {{start date|df=yes|2018|11|30}}
| stricter checking for bind, call, and apply
| stricter checking for <code>bind</code>, <code>call</code>, and <code>apply</code>
|-
|-
| 3.3
| 3.3
Line 297: Line 308:
|3.4
|3.4
| {{start date|df=yes|2019|03|29}}
| {{start date|df=yes|2019|03|29}}
|faster incremental builds, type inference from generic functions, readonly modifier for arrays, const assertions, type-checking global <code>this</code>
|faster incremental builds, type inference from generic functions, <code>readonly</code> modifier for arrays, <code>const</code> assertions, type-checking global <code>this</code>
|-
|-
|3.5
|3.5
Line 305: Line 316:
|3.6
|3.6
| {{start date|df=yes|2019|08|28}}
| {{start date|df=yes|2019|08|28}}
|Stricter generators, more accurate array spread, better unicode support for identifiers
|Stricter generators, more accurate array spread, better Unicode support for identifiers
|-
|-
|3.7
|3.7
| {{start date|df=yes|2019|11|05}}
| {{start date|df=yes|2019|11|05}}
|Optional Chaining, Nullish Coalescing
|Optional chaining, nullish coalescing
|-
|-
|3.8
|3.8
| {{start date|df=yes|2020|02|20}}
| {{start date|df=yes|2020|02|20}}
|Type-only imports and exports, ECMAScript private fields, top-level await
|Type-only imports and exports, ECMAScript private fields, top-level <code>await</code>
|-
|-
|3.9
|3.9
| {{start date|df=yes|2020|05|12}}
| {{start date|df=yes|2020|05|12}}
|Improvements in Inference, Speed Improvements
|Improvements in inference, speed improvements
|-
|-
|4.0
|4.0
| {{start date|df=yes|2020|08|20}}
| {{start date|df=yes|2020|08|20}}
|Variadic Tuple Types, Labeled Tuple Elements
|Variadic tuple types, labeled tuple elements
|-
|-
|4.1
|4.1
| {{start date|df=yes|2020|11|19}}
| {{start date|df=yes|2020|11|19}}
|Template Literal Types, Key Remapping in Mapped Types, Recursive Conditional Types
|Template literal types, key remapping in mapped types, recursive conditional types
|-
|-
|4.2
|4.2
| {{start date|df=yes|2021|02|25}}
| {{start date|df=yes|2021|02|25}}
|Smarter Type Alias Preservation, Leading/Middle Rest Elements in Tuple Types, Stricter Checks For The <code>in</code> Operator, <code>abstract</code> Construct Signatures
|Smarter type alias preservation, leading/middle rest elements in tuple types, stricter checks for the <code>in</code> operator, <code>abstract</code> construct signatures
|-
|-
|4.3
|4.3
| {{start date|df=yes|2021|05|26}}
| {{start date|df=yes|2021|05|26}}
|Separate Write Types on Properties, <code>override</code> and the <code>--noImplicitOverride</code> Flag, Template String Type Improvements
|Separate write types on properties, <code>override</code> and the <code>--noImplicitOverride</code> flag, template string type improvements
|-
|-
|4.4
|4.4
| {{start date|df=yes|2021|08|26}}
| {{start date|df=yes|2021|08|26}}
|Control Flow Analysis of Aliased Conditions and Discriminants, Symbol and Template String Pattern Index Signatures
|Control flow analysis of aliased conditions and discriminants, symbol and template string pattern index signatures
|-
|-
|4.5
|4.5
| {{start date|df=yes|2021|11|17}}
| {{start date|df=yes|2021|11|17}}
|Type and Promise Improvements, Supporting lib from node_modules, Template String Types as Discriminants, and es2022 module
|Type and promise improvements, supporting lib from <code>node_modules</code>, template string types as discriminants, and <code>es2022</code> module
|-
|-
|4.6
|4.6
| {{start date|df=yes|2022|02|28}}
| {{start date|df=yes|2022|02|28}}
|Type inference and checks improvements, support for ES2022 target, better ECMAScript handling
|See TypeScript 4.6 Microsoft release announcement [https://devblogs.microsoft.com/typescript/announcing-typescript-4-6/]
|-
|-
|4.7
|4.7
| {{start date|df=yes|2022|05|24}}
| {{start date|df=yes|2022|05|24}}
|Support for ES modules, instantiation expressions, variance annotations for type parameters, better control-flow checks and type check improvements
|See TypeScript 4.7 Microsoft release announcement [https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/]
|-
|-
|4.8
|4.8
| {{start date|df=yes|2022|08|25}}
| {{start date|df=yes|2022|08|25}}
|Intersection and union types improvements, better type inference
|See TypeScript 4.8 Microsoft release announcement [https://devblogs.microsoft.com/typescript/announcing-typescript-4-8/]
|-
|-
|4.9
|4.9
| {{start date|df=yes|2022|11|15}}
|15 November 2022
|<code>satisfies</code> operator, auto-accessors in classes (proposal), improvements in type narrowing and checks
|See TypeScript 4.9 Microsoft release announcement [https://devblogs.microsoft.com/typescript/announcing-typescript-4-9/]
|-
|-
|5.0
|5.0
| {{start date|df=yes|2023|03|16}}
|16 March 2023
|ES decorators (proposal), type inference improvements, <code>bundler</code> module resolution mode, speed and size optimizations
|See TypeScript 5.0 Microsoft release announcement [https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/]
|-
|5.1
| {{start date|df=yes|2023|06|01}}
|Easier implicit returns for <code>undefined</code> and unrelated types for getters and setters
|-
|5.2
| {{start date|df=yes|2023|08|24}}
|<code>using</code> declarations and explicit resource management, decorator metadata and named and anonymous tuple elements
|-
|5.3
| {{start date|df=yes|2023|11|20}}
|Improved type narrowing, correctness checks and performance optimizations
|-
|5.4
|6 March 2024
|<code>Object.groupBy</code> and <code>Map.groupBy</code> support
|-
|5.5 (Beta)
|25 April 2024
|Inferred Type Predicates, Regular Expression Syntax Checking, and Type Imports in JSDoc
|}
|}


Line 385: Line 416:
* [https://github.com/Microsoft/TypeScript/blob/730f18955dc17068be33691f0fb0e0285ebbf9f5/doc/spec.md TypeScript Language Specification]
* [https://github.com/Microsoft/TypeScript/blob/730f18955dc17068be33691f0fb0e0285ebbf9f5/doc/spec.md TypeScript Language Specification]
* [https://github.com/jbaron/cats CATS Cross Platform TypeScript Editor]
* [https://github.com/jbaron/cats CATS Cross Platform TypeScript Editor]
* {{open access}} [https://github.com/gibbok/typescript-book/tree/main The Concise TypeScript Book]
* {{open access}} {{YouTube|U6s2pdxebSo|TypeScript Origins: The Documentary}}


{{Programming languages}}
{{Programming languages}}
Line 405: Line 438:
[[Category:Source-to-source compilers]]
[[Category:Source-to-source compilers]]
[[Category:Statically typed programming languages]]
[[Category:Statically typed programming languages]]

[[tk:TypeScript]]

Latest revision as of 19:33, 4 May 2024

TypeScript
ParadigmMulti-paradigm: functional, generic, imperative, object-oriented
Designed byMicrosoft
DeveloperMicrosoft
First appeared1 October 2012; 11 years ago (2012-10-01)[1]
Stable release
5.4.2[2] Edit this on Wikidata / 6 March 2024; 3 months ago (6 March 2024)
Typing disciplineDuck, gradual, structural[3]
LicenseApache License 2.0
Filename extensions.ts, .tsx, .mts, .cts
Websitewww.typescriptlang.org
Influenced by
C#, F#,[4] Java, JavaScript, ActionScript[5]
Influenced
AtScript, AssemblyScript, ArkTS

TypeScript is a free and open-source high-level programming language developed by Microsoft that adds static typing with optional type annotations to JavaScript. It is designed for the development of large applications and transpiles to JavaScript.[6] Because TypeScript is a superset of JavaScript, all JavaScript programs are syntactically valid TypeScript, but they can fail to type-check for safety reasons.

TypeScript may be used to develop JavaScript applications for both client-side and server-side execution (as with Node.js, Deno or Bun). Multiple options are available for transpilation. The default TypeScript Compiler can be used,[7] or the Babel compiler can be invoked to convert TypeScript to JavaScript.

TypeScript supports definition files that can contain type information of existing JavaScript libraries, much like C++ header files can describe the structure of existing object files. This enables other programs to use the values defined in the files as if they were statically typed TypeScript entities. There are third-party header files for popular libraries such as jQuery, MongoDB, and D3.js. TypeScript headers for the Node.js library modules are also available, allowing development of Node.js programs within TypeScript.[8]

The TypeScript compiler is itself written in TypeScript and compiled to JavaScript. It is licensed under the Apache License 2.0. Anders Hejlsberg, lead architect of C# and creator of Delphi and Turbo Pascal, has worked on the development of TypeScript.[9][10][11][12]

History[edit]

TypeScript was released to the public in October 2012, with version 0.8, after two years of internal development at Microsoft.[13][14] Soon after the initial public release, Miguel de Icaza praised the language itself, but criticized the lack of mature IDE support apart from Microsoft Visual Studio, which was not available on Linux and OS X at that time.[15][16] As of April 2021 there is support in other IDEs and text editors, including Emacs, Vim, WebStorm, Atom[17] and Microsoft's own Visual Studio Code.[18] TypeScript 0.9, released in 2013, added support for generics.[19]

TypeScript 1.0 was released at Microsoft's Build developer conference in 2014.[20] Visual Studio 2013 Update 2 provides built-in support for TypeScript.[21] Further improvement were made in July 2014, when the development team announced a new TypeScript compiler, asserted to have a five-fold performance increase. Simultaneously, the source code, which was initially hosted on CodePlex, was moved to GitHub.[22]

On 22 September 2016, TypeScript 2.0 was released, introducing several features, including the ability for programmers to optionally enforce null safety,[23] to mitigate what's sometimes referred to as the billion-dollar mistake.

TypeScript 3.0 was released on 30 July 2018,[24] bringing many language additions like tuples in rest parameters and spread expressions, rest parameters with tuple types, generic rest parameters and so on.[25]

TypeScript 4.0 was released on 20 August 2020.[26] While 4.0 did not introduce any breaking changes, it added language features such as Custom JSX Factories and Variadic Tuple Types.[26]

TypeScript 5.0 was released on 16 March 2023 and included support for decorators.[27]

Design[edit]

TypeScript originated from the shortcomings of JavaScript for the development of large-scale applications both at Microsoft and among their external customers.[28] Challenges with dealing with complex JavaScript code led to demand for custom tooling to ease developing of components in the language.[29]

TypeScript developers sought a solution that would not break compatibility with the standard and its cross-platform support. Knowing that the current ECMAScript standard proposal promised future support for class-based programming, TypeScript was based on that proposal. That led to a JavaScript compiler with a set of syntactical language extensions, a superset based on the proposal, that transforms the extensions into regular JavaScript. In this sense, the class feature of TypeScript was a preview of what to expect from ECMAScript 2015. A unique aspect not in the proposal, but added to TypeScript, is optional static typing (also known as gradual typing) that enables static language analysis to facilitate tooling and IDE support.

ECMAScript 2015 support[edit]

TypeScript adds support for features such as classes, modules, and an arrow function syntax as defined in the ECMAScript 2015 standard.

Features[edit]

TypeScript is a language extension that adds features to ECMAScript 6. Additional features include:

The following features are backported from ECMAScript 2015:

Syntactically, TypeScript is very similar to JScript .NET, another Microsoft implementation of the ECMA-262 language standard that added support for static typing and classical object-oriented language features such as classes, inheritance, interfaces, and namespaces.

Compatibility with JavaScript[edit]

TypeScript is a strict superset of ECMAScript 2015, which is itself a superset of ECMAScript 5, commonly referred to as JavaScript.[32] As such, a JavaScript program is also a valid TypeScript program and a TypeScript program can seamlessly consume JavaScript. By default the compiler targets ECMAScript 5, the current prevailing standard, but is also able to generate constructs used in ECMAScript 3 or 2015.

With TypeScript, it is possible to use existing JavaScript code, incorporate popular JavaScript libraries, and call TypeScript-generated code from other JavaScript.[33] Type declarations for these libraries are provided with the source code.

Type annotations[edit]

TypeScript provides static typing through type annotations to enable type checking at compile time. This is optional and can be ignored to use the regular dynamic typing of JavaScript.

function add(left: number, right: number): number {
	return left + right;
}

Primitive types are annotated using the types number, boolean, and string. These types are distinct from their class counterparts (Number, Boolean, etc), which cannot have operations performed from values directly. For instance, a Number and a number cannot be added. There is additionally undefined and null types for their respective values.

All other types are annotated using their class name rather than primitives, such as Error. Arrays can be written in two different ways which are both syntactically the same: the generic-based syntax Array<T> and a shorthand with T[].

Additional built-in data types are tuples, unions, never and any:

  • An array with predefined data types at each index is a tuple, represented as [type1, type2, ..., typeN].
  • A variable that can hold more than one type of data is a union, represented using the logical OR | symbol (string | number).
  • The never type is used when a given type should be impossible to create, which is useful for filtering mapped types.
  • A value of type any supports the same operations as a value in JavaScript and minimal static type checking is performed,[34] which makes it suitable for weakly or dynamically-typed structures, although this is generally discouraged practice.[35]

Type annotations can be exported to a separate declarations file to make type information available for TypeScript scripts using types already compiled into JavaScript. Annotations can be declared for an existing JavaScript library, as has been done for Node.js and jQuery.

The TypeScript compiler makes use of type inference to infer types when types are not given. For example, the add method in the code above would be inferred as returning a number even if no return type annotation had been provided. This is based on the static types of left and right being numbers, and the compiler's knowledge that the result of adding two numbers is always a number. However, explicitly declaring the return type allows the compiler to verify correctness.

If no type can be inferred because of lack of declarations (such as in a JavaScript module without types), then it defaults to the dynamic any type. Additional module types can be provided using a .d.ts declaration file using the declare module "moduleName" syntax.

Declaration files[edit]

When a TypeScript script gets compiled there is an option to generate a declaration file (with the extension .d.ts) that functions as an interface to the components in the compiled JavaScript. In the process the compiler strips away all function and method bodies and preserves only the signatures of the types that are exported. The resulting declaration file can then be used to describe the exported virtual TypeScript types of a JavaScript library or module when a third-party developer consumes it from TypeScript.

The concept of declaration files is analogous to the concept of header files found in C/C++.

declare namespace Arithmetics {
    add(left: number, right: number): number;
    subtract(left: number, right: number): number;
    multiply(left: number, right: number): number;
    divide(left: number, right: number): number;
}

Type declaration files can be written by hand for existing JavaScript libraries, as has been done for jQuery and Node.js.

Large collections of declaration files for popular JavaScript libraries are hosted on GitHub in DefinitelyTyped.

Generics[edit]

TypeScript supports generic programming using a syntax similar to Java.[36] The following is an example of the identity function.[37]

function id<T>(x: T): T {
    return x;
}

Classes[edit]

TypeScript uses the same annotation style for class methods and fields as for functions and variables respectively. Compared with vanilla JavaScript classes, a TypeScript class can also implement an interface through the implements keyword, use generic parameters similarly to Java, and specify public and private fields.

class Person {
    private name: string;
    private age: number;
    private salary: number;

    constructor(name: string, age: number, salary: number) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }

    toString(): string {
        return `${this.name} (${this.age}) (${this.salary})`;
    }
}

Union types[edit]

Union types are supported in TypeScript.[38] The values are implicitly "tagged" with a type by the language, and may be retrieved using a typeof call for primitive values and an instanceof comparison for complex data types. Types with overlapping usage (e.g. a slice method exists on both strings and arrays, the plus operator works on both strings and numbers) don't need additional narrowing to use these features.

function successor(n: number | bigint): number | bigint {
    // types that support the same operations don't need narrowing
    return ++n;
}

function dependsOnParameter(v: string | Array<string> | number) {
    // distinct types need narrowing
    if (v instanceof Array) {
        // do something
    } else if (typeof(v) === "string") {
        // do something else
    } else {
        // has to be a number
    }
}

Enumerated types[edit]

TypeScript adds an 'enum' data type to JavaScript.

enum Cardsuit {Clubs, Diamonds, Hearts, Spades};
var c: Cardsuit = Cardsuit.Diamonds;

By default, enums number members starting at 0; this can be overridden by setting the value of the first:

enum Cardsuit {Clubs = 1, Diamonds, Hearts, Spades};
var c: Cardsuit = Cardsuit.Diamonds;

All the values can be set:

enum Cardsuit {Clubs = 1, Diamonds = 2, Hearts = 4, Spades = 8};
var c: Cardsuit = Cardsuit.Diamonds;

TypeScript supports mapping the numeric value to its name. For example, this finds the name of the value 2:

enum Cardsuit {Clubs = 1, Diamonds, Hearts, Spades};
var suitName: string = Cardsuit[2];

alert(suitName);

Modules and namespaces[edit]

TypeScript distinguishes between modules and namespaces. Both features in TypeScript support encapsulation of classes, interfaces, functions and variables into containers. Namespaces (formerly internal modules) utilize JavaScript immediately-invoked function expressions to encapsulate code, whereas modules (formerly external modules) leverage JavaScript library patterns to do so (AMD or CommonJS).[39]

Development tools[edit]

Compiler[edit]

The TypeScript compiler, named tsc, is written in TypeScript. As a result, it can be compiled into regular JavaScript and can then be executed in any JavaScript engine (e.g. a browser). The compiler package comes bundled with a script host that can execute the compiler. It is also available as a Node.js package that uses Node.js as a host.

The compiler can "target" a particular edition of ECMAScript (such as ES5 for legacy browser compatibility), but by default compiles to the latest version.

IDE and editor support[edit]

  • Microsoft provides a plug-in for Visual Studio 2012 and WebMatrix, full integrated support in Visual Studio 2013, Visual Studio 2015, and basic text editor support for Emacs and Vim.[40]
  • Visual Studio Code supports TypeScript in addition to several other languages, and offers features like debugging and intelligent code completion.
  • alm.tools is an open source cloud IDE for TypeScript built using TypeScript, ReactJS and TypeStyle.
  • JetBrains supports TypeScript with code completion, refactoring and debugging in its IDEs built on IntelliJ platform, such as PhpStorm 6, WebStorm 6, and IntelliJ IDEA,[41] as well as their Visual Studio Add-in and extension, ReSharper 8.1.[42][43]
  • Atom has a TypeScript plugin with support for code completion, navigation, formatting, and fast compilation.[44]
  • The online Cloud9 IDE and Codenvy support TypeScript.
  • A plugin is available for the NetBeans IDE.
  • A plugin is available for the Eclipse IDE (version Kepler)
  • TypEcs is available for the Eclipse IDE.
  • The Cross Platform Cloud IDE Codeanywhere supports TypeScript.
  • Webclipse An Eclipse plugin designed to develop TypeScript and Angular 2.
  • Angular IDE A standalone IDE available via npm to develop TypeScript and Angular 2 applications, with integrated terminal support.
  • Tide – TypeScript Interactive Development Environment for Emacs.

Integration with build automation tools[edit]

Using plug-ins, TypeScript can be integrated with build automation tools, including Grunt (grunt-ts[45]), Apache Maven (TypeScript Maven Plugin[46]), Gulp (gulp-typescript[47]) and Gradle (TypeScript Gradle Plugin[48]).

Linting tools[edit]

TSLint[49] scans TypeScript code for conformance to a set of standards and guidelines. ESLint, a standard JavaScript linter, also provided some support for TypeScript via community plugins. However, ESLint's inability to leverage TypeScript's language services precluded certain forms of semantic linting and program-wide analysis.[50] In early 2019, the TSLint team announced the linter's deprecation in favor of typescript-eslint, a joint effort of the TSLint, ESLint and TypeScript teams to consolidate linting under the ESLint umbrella for improved performance, community unity and developer accessibility.[51]

CodeDOM Provider[edit]

CodeDOM[52] provides types that represent common types of source code elements, which will be transformed to data types, classes and statements etc. of a programming language through a CodeDOMProvider.[53] Programmers use CodeDOM and a CodeDOM provider to construct a code generator that generates codes for an application domain. TypeScript CodeDOM Provider[54] generates TypeScript codes according to a CodeDOM.

Release history[edit]

Version number Release date Significant changes
0.8 1 October 2012 (2012-10-01)
0.9 18 June 2013 (2013-06-18)
1.0 12 April 2014 (2014-04-12)
1.1 6 October 2014 (2014-10-06) performance improvements
1.3 12 November 2014 (2014-11-12) protected modifier, tuple types
1.4 20 January 2015 (2015-01-20) union types, let and const declarations, template strings, type guards, type aliases
1.5 20 July 2015 (2015-07-20) ES6 modules, namespace keyword, for..of support, decorators
1.6 16 September 2015 (2015-09-16) JSX support, intersection types, local type declarations, abstract classes and methods, user-defined type guard functions
1.7 30 November 2015 (2015-11-30) async and await support,
1.8 22 February 2016 (2016-02-22) constraints generics, control flow analysis errors, string literal types, allowJs
2.0 22 September 2016 (2016-09-22) null- and undefined-aware types, control flow based type analysis, discriminated union types, never type, readonly keyword, type of this for functions
2.1 8 November 2016 (2016-11-08) keyof and lookup types, mapped types, object spread and rest,
2.2 22 February 2017 (2017-02-22) mix-in classes, object type,
2.3 27 April 2017 (2017-04-27) async iteration, generic parameter defaults, strict option
2.4 27 June 2017 (2017-06-27) dynamic import expressions, string enums, improved inference for generics, strict contravariance for callback parameters
2.5 31 August 2017 (2017-08-31) optional catch clause variables
2.6 31 October 2017 (2017-10-31) strict function types
2.7 31 January 2018 (2018-01-31) constant-named properties, fixed-length tuples
2.8 27 March 2018 (2018-03-27) conditional types, improved keyof with intersection types
2.9 14 May 2018 (2018-05-14) support for symbols and numeric literals in keyof and mapped object types
3.0 30 July 2018 (2018-07-30) project references, extracting and spreading parameter lists with tuples
3.1 27 September 2018 (2018-09-27) mappable tuple and array types
3.2 30 November 2018 (2018-11-30) stricter checking for bind, call, and apply
3.3 31 January 2019 (2019-01-31) relaxed rules on methods of union types, incremental builds for composite projects
3.4 29 March 2019 (2019-03-29) faster incremental builds, type inference from generic functions, readonly modifier for arrays, const assertions, type-checking global this
3.5 29 May 2019 (2019-05-29) faster incremental builds, omit helper type, improved excess property checks in union types, smarter union type checking
3.6 28 August 2019 (2019-08-28) Stricter generators, more accurate array spread, better Unicode support for identifiers
3.7 5 November 2019 (2019-11-05) Optional chaining, nullish coalescing
3.8 20 February 2020 (2020-02-20) Type-only imports and exports, ECMAScript private fields, top-level await
3.9 12 May 2020 (2020-05-12) Improvements in inference, speed improvements
4.0 20 August 2020 (2020-08-20) Variadic tuple types, labeled tuple elements
4.1 19 November 2020 (2020-11-19) Template literal types, key remapping in mapped types, recursive conditional types
4.2 25 February 2021 (2021-02-25) Smarter type alias preservation, leading/middle rest elements in tuple types, stricter checks for the in operator, abstract construct signatures
4.3 26 May 2021 (2021-05-26) Separate write types on properties, override and the --noImplicitOverride flag, template string type improvements
4.4 26 August 2021 (2021-08-26) Control flow analysis of aliased conditions and discriminants, symbol and template string pattern index signatures
4.5 17 November 2021 (2021-11-17) Type and promise improvements, supporting lib from node_modules, template string types as discriminants, and es2022 module
4.6 28 February 2022 (2022-02-28) Type inference and checks improvements, support for ES2022 target, better ECMAScript handling
4.7 24 May 2022 (2022-05-24) Support for ES modules, instantiation expressions, variance annotations for type parameters, better control-flow checks and type check improvements
4.8 25 August 2022 (2022-08-25) Intersection and union types improvements, better type inference
4.9 15 November 2022 (2022-11-15) satisfies operator, auto-accessors in classes (proposal), improvements in type narrowing and checks
5.0 16 March 2023 (2023-03-16) ES decorators (proposal), type inference improvements, bundler module resolution mode, speed and size optimizations
5.1 1 June 2023 (2023-06-01) Easier implicit returns for undefined and unrelated types for getters and setters
5.2 24 August 2023 (2023-08-24) using declarations and explicit resource management, decorator metadata and named and anonymous tuple elements
5.3 20 November 2023 (2023-11-20) Improved type narrowing, correctness checks and performance optimizations
5.4 6 March 2024 Object.groupBy and Map.groupBy support
5.5 (Beta) 25 April 2024 Inferred Type Predicates, Regular Expression Syntax Checking, and Type Imports in JSDoc

See also[edit]

References[edit]

Citations[edit]

  1. ^ "TypeScript". CodePlex. Archived from the original on 3 April 2015. Retrieved 26 April 2015.
  2. ^ "Release TypeScript 5.4 microsoft/TypeScript". 6 March 2024. Retrieved 19 March 2024.
  3. ^ "Type Compatibility". TypeScript. Retrieved 21 March 2018.
  4. ^ "The Early History of F#" (PDF). TypeScript was directly influenced by F#: one of the originators of TypeScript was Luke Hoban, who began TypeScript (then called Strada) immediately after working on F# 2.0. Recently he noted the influence of F# on early parts of the TypeScript design [Hoban 2017].
  5. ^ Nelson, Gary (28 April 2020). "How ActionScript foreshadowed TypeScript". Medium. Retrieved 9 July 2022.
  6. ^ Bright, Peter (3 October 2012). "Microsoft TypeScript: the JavaScript we need, or a solution looking for a problem?". Ars Technica. Condé Nast. Retrieved 26 April 2015.
  7. ^ "TypeScript Programming with Visual Studio Code". code.visualstudio.com. Retrieved 12 February 2019.
  8. ^ "borisyankov/DefinitelyTyped". GitHub. Retrieved 26 April 2015.
  9. ^ Foley, Mary Jo (1 October 2012). "Microsoft takes the wraps off TypeScript, a superset of JavaScript". ZDNet. CBS Interactive. Retrieved 26 April 2015.
  10. ^ Somasegar, S. (1 October 2012). "Somasegar's blog". Microsoft. Retrieved 26 April 2015.
  11. ^ Baxter-Reynolds, Matt (1 October 2012). "Microsoft TypeScript: Can the father of C# save us from the tyranny of JavaScript?". ZDNet. Retrieved 26 April 2015.
  12. ^ Jackson, Joab (1 October 2012). "Microsoft Augments Javascript for Large-scale Development". CIO. IDG Enterprise. Archived from the original on 17 December 2013. Retrieved 26 April 2015.
  13. ^ "Microsoft augments JavaScript for large-scale development". InfoWorld. IDG. 1 October 2012. Retrieved 26 April 2015.
  14. ^ Turner, Jonathan (2 April 2014). "Announcing TypeScript 1.0". TypeScript Language team blog. Microsoft. Retrieved 20 October 2021.
  15. ^ Miguel de Icaza (1 October 2012). "TypeScript: First Impressions". Retrieved 12 October 2012. But TypeScript only delivers half of the value in using a strongly typed language to Unix developers: strong typing. Intellisense, code completion and refactoring are tools that are only available to Visual Studio Professional users on Windows. There is no Eclipse, MonoDevelop or Emacs support for any of the language features
  16. ^ "Microsoft TypeScript: Can the father of C# save us from the tyranny of JavaScript?". ZDNet. 1 October 2012. Retrieved 12 October 2012. And I think this is a pretty big misstep. If you're building web apps that run on anything other than Windows, you're likely using a Mac and most likely not using Visual Studio. You need the Visual Studio plug-in to get the IntelliSense. All you get without Visual Studio is the strong-typing. You don't get the productivity benefits you get from IntelliSense..
  17. ^ "TypeStrong: The only TypeScript package you will ever need". GitHub. Retrieved 21 July 2016.
  18. ^ Hillar, Gastón (14 May 2013). "Working with TypeScript in Visual Studio 2012". Dr. Dobb's Journal. Retrieved 26 April 2015.
  19. ^ "TypeScript 0.9 arrives with new compiler, support for generics". The Register. 18 June 2013. Retrieved 26 April 2015.
  20. ^ Hejlsberg, Anders (2 April 2014). "TypeScript". Channel 9. Microsoft. Retrieved 26 April 2015.
  21. ^ Jackson, Joab (25 February 2014). "Microsoft TypeScript graduates to Visual Studio". PC World. IDG. Retrieved 26 April 2015.
  22. ^ Turner, Jonathan (21 July 2014). "New Compiler and Moving to GitHub". TypeScript Language team blog. Microsoft. Retrieved 26 April 2015.[permanent dead link]
  23. ^ Bright, Peter (22 September 2016). "TypeScript, Microsoft's JavaScript for big applications, reaches version 2.0". Ars Technica. Condé Nast. Retrieved 22 September 2016.
  24. ^ "Announcing TypeScript 3.0". 30 July 2018. Retrieved 16 March 2020.
  25. ^ "TypeScript 3.0". 30 July 2018. Retrieved 16 March 2020.
  26. ^ a b "Announcing TypeScript 4.0". TypeScript. 20 August 2020. Retrieved 30 October 2020.
  27. ^ "Documentation - TypeScript 5.0". www.typescriptlang.org. Retrieved 18 May 2023.
  28. ^ Anders Hejlsberg (5 October 2012). "What is TypeScript and why with Anders Hejlsberg". www.hanselminutes.com. Retrieved 15 January 2014.
  29. ^ S. Somasegar (1 October 2012). "TypeScript: JavaScript Development at Application Scale". msdn.com. Retrieved 27 November 2013.
  30. ^ "Documentation - TypeScript 5.2". www.typescriptlang.org. Retrieved 9 November 2023.
  31. ^ Klint Finley (1 October 2012). "Microsoft Previews New JavaScript-Like Programming Language TypeScript". TechCrunch. Retrieved 27 November 2013.
  32. ^ "Angular 2". angular.io. Retrieved 4 May 2016.
  33. ^ "Welcome to TypeScript". typescriptlang.org. Microsoft. Retrieved 26 April 2015.
  34. ^ "TypeScript Language Specification p.24" (PDF). Archived from the original (PDF) on 17 November 2013.
  35. ^ "TypeScript: Documentation - Everyday Types". www.typescriptlang.org/. Retrieved 30 March 2021.
  36. ^ Turner, Jonathan (18 June 2013). "Announcing TypeScript 0.9". TypeScript Language team blog. Microsoft.
  37. ^ "Generics in Typescript". Microsoft.
  38. ^ "Handbook - Unions and Intersection Types". www.typescriptlang.org. Retrieved 30 November 2020.
  39. ^ Sönke Sothmann (31 January 2014). "An introduction to TypeScript's module system". blog.oio.de. Archived from the original on 1 February 2014. Retrieved 21 February 2014.
  40. ^ Olivier Bloch (1 October 2012). "Sublime Text, Vi, Emacs: TypeScript enabled!". Microsoft. Retrieved 28 October 2012.
  41. ^ "TypeScript support in WebStorm 6". JetBrains.
  42. ^ "TypeScript support in ReSharper 8.1". JetBrains. 28 October 2013.
  43. ^ "ReSharper: The Visual Studio Extension for .NET Developers by JetBrains". JetBrains.
  44. ^ "atom-typescript". Atom. Retrieved 9 January 2020.
  45. ^ "TypeStrong/grunt-ts". GitHub. Retrieved 26 April 2015.
  46. ^ "ppedregal/typescript-maven-plugin". GitHub. Retrieved 26 April 2015.
  47. ^ "ivogabe/gulp-typescript". GitHub. Retrieved 14 July 2017.
  48. ^ "sothmann/typescript-gradle-plugin". GitHub. Retrieved 26 April 2015.
  49. ^ "TSLint". palantir.github.io.
  50. ^ Palantir (19 February 2019). "TSLint in 2019". Medium. Retrieved 24 April 2019.
  51. ^ "TSLint Deprecated to Focus Support on typescript-eslint". InfoQ. Retrieved 24 April 2019.
  52. ^ "CodeDOM". learn.microsoft.com.
  53. ^ "CodeDOMProvider". learn.microsoft.com.
  54. ^ "TypeScript CodeDOM Provider". github.com.

Sources[edit]

External links[edit]