codefinance.training

Coding for Finance

TypeScript

TypeScript

Tab nameTab nameTab name
Tab content
Tab content
Tab content
AboutBooks

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

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

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

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

Features

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

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

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

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

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

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

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

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

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

Compiler

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

  • 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

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

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

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

See also

References

Citations

  1. ^ "TypeScript". CodePlex. Archived from the original on 3 April 2015. Retrieved 26 April 2015.
  2. ^ "Release 5.5.3". 2 July 2024. Retrieved 10 July 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. Archived from the original on 22 July 2014. Retrieved 26 April 2015.
  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

External links


Comments are closed.