Documentation - TypeScript 1.5 (2023)

ES6 Modules

TypeScript 1.5 supports ECMAScript 6 (ES6) modules.ES6 modules are effectively TypeScript external modules with a new syntax: ES6 modules are separately loaded source files that possibly import other modules and provide a number of externally accessible exports.ES6 modules feature several new export and import declarations.It is recommended that TypeScript libraries and applications be updated to use the new syntax, but this is not a requirement.The new ES6 module syntax coexists with TypeScript’s original internal and external module constructs and the constructs can be mixed and matched at will.

Export Declarations

In addition to the existing TypeScript support for decorating declarations with export, module members can also be exported using separate export declarations, optionally specifying different names for exports using as clauses.

ts

interface Stream { ... }

function writeToStream(stream: Stream, data: string) { ... }

export { Stream, writeToStream as write }; // writeToStream exported as write

Import declarations, as well, can optionally use as clauses to specify different local names for the imports. For example:

ts

import { read, write, standardOutput as stdout } from "./inout";

var s = read(stdout);

write(stdout, s);

As an alternative to individual imports, a namespace import can be used to import an entire module:

ts

import * as io from "./inout";

var s = io.read(io.standardOutput);

io.write(io.standardOutput, s);

Re-exporting

Using from clause a module can copy the exports of a given module to the current module without introducing local names.

ts

export { read, write, standardOutput as stdout } from "./inout";

export * can be used to re-export all exports of another module. This is useful for creating modules that aggregate the exports of several other modules.

ts

export function transform(s: string): string { ... }

export * from "./mod1";

export * from "./mod2";

Default Export

An export default declaration specifies an expression that becomes the default export of a module:

ts

export default class Greeter {

sayHello() {

console.log("Greetings!");

}

}

Which in turn can be imported using default imports:

ts

import Greeter from "./greeter";

var g = new Greeter();

g.sayHello();

(Video) TypeScript is Literal Magic

Bare Import

A “bare import” can be used to import a module only for its side-effects.

ts

import "./polyfills";

For more information about module, please see the ES6 module support spec.

Destructuring in declarations and assignments

TypeScript 1.5 adds support to ES6 destructuring declarations and assignments.

Declarations

A destructuring declaration introduces one or more named variables and initializes them with values extracted from properties of an object or elements of an array.

For example, the following sample declares variables x, y, and z, and initializes them to getSomeObject().x, getSomeObject().y and getSomeObject().z respectively:

ts

var { x, y, z } = getSomeObject();

Destructuring declarations also works for extracting values from arrays:

ts

var [x, y, z = 10] = getSomeArray();

Similarly, destructuring can be used in function parameter declarations:

ts

function drawText({ text = "", location: [x, y] = [0, 0], bold = false }) {

// Draw text

}

// Call drawText with an object literal

var item = { text: "someText", location: [1, 2, 3], style: "italics" };

drawText(item);

Assignments

Destructuring patterns can also be used in regular assignment expressions.For instance, swapping two variables can be written as a single destructuring assignment:

ts

var x = 1;

var y = 2;

[x, y] = [y, x];

namespace keyword

TypeScript used the module keyword to define both “internal modules” and “external modules”;this has been a bit of confusion for developers new to TypeScript.“Internal modules” are closer to what most people would call a namespace; likewise, “external modules” in JS speak really just are modules now.

Note: Previous syntax defining internal modules are still supported.

Before:

ts

module Math {

export function add(x, y) { ... }

}

After:

ts

namespace Math {

export function add(x, y) { ... }

}

(Video) AI documentation writer for TS and JS in VSCode

let and const support

ES6 let and const declarations are now supported when targeting ES3 and ES5.

Const

ts

const MAX = 100;

++MAX; // Error: The operand of an increment or decrement

// operator cannot be a constant.

Block scoped

ts

if (true) {

let a = 4;

// use a

} else {

let a = "string";

// use a

}

alert(a); // Error: a is not defined in this scope.

for..of support

TypeScript 1.5 adds support to ES6 for..of loops on arrays for ES3/ES5 as well as full support for Iterator interfaces when targeting ES6.

Example

The TypeScript compiler will transpile for..of arrays to idiomatic ES3/ES5 JavaScript when targeting those versions:

ts

for (var v of expr) {

}

will be emitted as:

js

for (var _i = 0, _a = expr; _i < _a.length; _i++) {

var v = _a[_i];

}

Decorators

TypeScript decorators are based on the ES7 decorator proposal.

A decorator is:

  • an expression
  • that evaluates to a function
  • that takes the target, name, and property descriptor as arguments
  • and optionally returns a property descriptor to install on the target object

For more information, please see the Decorators proposal.

Example

Decorators readonly and enumerable(false) will be applied to the property method before it is installed on class C.This allows the decorator to change the implementation, and in this case, augment the descriptor to be writable: false and enumerable: false.

ts

class C {

@readonly

@enumerable(false)

method() { ... }

}

function readonly(target, key, descriptor) {

descriptor.writable = false;

}

function enumerable(value) {

return function (target, key, descriptor) {

(Video) TypeScript Tutorial #18 - Generics

descriptor.enumerable = value;

};

}

Computed properties

Initializing an object with dynamic properties can be a bit of a burden. Take the following example:

ts

type NeighborMap = { [name: string]: Node };

type Node = { name: string; neighbors: NeighborMap };

function makeNode(name: string, initialNeighbor: Node): Node {

var neighbors: NeighborMap = {};

neighbors[initialNeighbor.name] = initialNeighbor;

return { name: name, neighbors: neighbors };

}

Here we need to create a variable to hold on to the neighbor-map so that we can initialize it.With TypeScript 1.5, we can let the compiler do the heavy lifting:

ts

function makeNode(name: string, initialNeighbor: Node): Node {

return {

name: name,

neighbors: {

[initialNeighbor.name]: initialNeighbor,

},

};

}

Support for UMD and System module output

In addition to AMD and CommonJS module loaders, TypeScript now supports emitting modules UMD (Universal Module Definition) and System module formats.

Usage:

tsc —module umd

and

tsc —module system

Unicode codepoint escapes in strings

ES6 introduces escapes that allow users to represent a Unicode codepoint using just a single escape.

As an example, consider the need to escape a string that contains the character ’𠮷‘.In UTF-16/UCS2, ’𠮷’ is represented as a surrogate pair, meaning that it’s encoded using a pair of 16-bit code units of values, specifically 0xD842 and 0xDFB7.Previously this meant that you’d have to escape the codepoint as "\uD842\uDFB7".This has the major downside that it’s difficult to discern two independent characters from a surrogate pair.

With ES6’s codepoint escapes, you can cleanly represent that exact character in strings and template strings with a single escape: "\u{20bb7}".TypeScript will emit the string in ES3/ES5 as "\uD842\uDFB7".

Tagged template strings in ES3/ES5

In TypeScript 1.4, we added support for template strings for all targets, and tagged templates for just ES6.Thanks to some considerable work done by @ivogabe, we bridged the gap for for tagged templates in ES3 and ES5.

When targeting ES3/ES5, the following code

ts

function oddRawStrings(strs: TemplateStringsArray, n1, n2) {

return strs.raw.filter((raw, index) => index % 2 === 1);

}

oddRawStrings`Hello \n${123} \t ${456}\n world`;

will be emitted as

js

function oddRawStrings(strs, n1, n2) {

(Video) TypeScript Tutorial for Beginners

return strs.raw.filter(function (raw, index) {

return index % 2 === 1;

});

}

(_a = ["Hello \n", " \t ", "\n world"]),

(_a.raw = ["Hello \\n", " \\t ", "\\n world"]),

oddRawStrings(_a, 123, 456);

var _a;

AMD-dependency optional names

/// <amd-dependency path="x" /> informs the compiler about a non-TS module dependency that needs to be injected in the resulting module’s require call;however, there was no way to consume this module in the TS code.

The new amd-dependency name property allows passing an optional name for an amd-dependency:

ts

/// <amd-dependency path="legacy/moduleA" name="moduleA"/>

declare var moduleA: MyType;

moduleA.callStuff();

Generated JS code:

js

define(["require", "exports", "legacy/moduleA"], function (

require,

exports,

moduleA

) {

moduleA.callStuff();

});

Project support through tsconfig.json

Adding a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project.The tsconfig.json file specifies the root files and the compiler options required to compile the project. A project is compiled in one of the following ways:

  • By invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.
  • By invoking tsc with no input files and a -project (or just -p) command line option that specifies the path of a directory containing a tsconfig.json file.
Example

{

"compilerOptions": {

"module": "commonjs",

"noImplicitAny": true,

"sourceMap": true

}

}

See the tsconfig.json wiki page for more details.

--rootDir command line option

Option outDir duplicates the input hierarchy in the output.The compiler computes the root of the input files as the longest common path of all input files;and then uses that to replicate all its substructure in the output.

Sometimes this is not desirable, for instance inputs FolderA\FolderB\1.ts and FolderA\FolderB\2.ts would result in output structure mirroring FolderA\FolderB\.Now if a new file FolderA\3.ts is added to the input, the output structure will pop out to mirror FolderA\.

rootDir specifies the input directory to be mirrored in output instead of computing it.

--noEmitHelpers command line option

The TypeScript compiler emits a few helpers like __extends when needed.The helpers are emitted in every file they are referenced in.If you want to consolidate all helpers in one place, or override the default behavior, use noEmitHelpers to instructs the compiler not to emit them.

(Video) TYPESCRIPT VS JAVASCRIPT - FULL COMPARISON IN 5 MIN

--newLine command line option

By default the output new line character is \r\n on Windows based systems and \n on *nix based systems.newLine command line flag allows overriding this behavior and specifying the new line character to be used in generated output files.

--inlineSourceMap and inlineSources command line options

inlineSourceMap causes source map files to be written inline in the generated .js files instead of in a independent .js.map file.inlineSources allows for additionally inlining the source .ts file into the .js file.

FAQs

How long does it take to master TypeScript? ›

How Long Does it Take to Learn TypeScript? It takes about a month to learn the basics of TypeScript, assuming you study for at least one hour a day. Expect to spend at least six months studying TypeScript before you develop the skills you need to apply it in a professional development setting.

Is it hard to learn TypeScript? ›

For many projects – especially medium to large projects – TypeScript will save you lots of time and headaches. And if you already know JavaScript, TypeScript won't be too hard to learn. It's a great tool to have in your arsenal.

How much JavaScript is required for TypeScript? ›

Learning JavaScript and TypeScript

The answer is that you can't learn TypeScript without learning JavaScript! TypeScript shares syntax and runtime behavior with JavaScript, so anything you learn about JavaScript is helping you learn TypeScript at the same time.

How to be better at TypeScript? ›

10 Quick Tips I Have Learned Using TypeScript
  1. Use the Unknown Type Before Defaulting to Any. ...
  2. The Never Type Can Be Handy for Error Handling. ...
  3. Interfaces vs. ...
  4. Learn To Use Generic Types. ...
  5. The Partial Utility Type Could Be Your New Best Friend. ...
  6. Other Utility Types You Should Know.
Mar 18, 2022

Can I learn TypeScript in 2 days? ›

If TypeScript is your first language, it will likely take you anywhere from 3 months to a year to learn. Mainly because you need to learn JavaScript and type systems as well! However, if you understand JavaScript and how type systems work, you can easily get the basics of TypeScript down within a day to a week.

Is TypeScript more difficult than JavaScript? ›

JavaScript is interpreted, easier to learn, and the best choice for smaller projects. Meanwhile, TypeScript is compiled, harder to learn, and best used for complex and large-scale projects.

Which is faster TypeScript or Python? ›

In terms of raw performance, Typescript is much faster than Python. When coding memory-intensive tasks in Python, e.g games, that utilize high-end 3D graphics, the CPU begins to take a hit and there is a significant drop in performance. Unlike Typescript, Python is not asynchronous at its core.

Is TypeScript easy than JavaScript? ›

TypeScript code typically won't perform any differently than JavaScript code, since it's transpiled to JavaScript before running. But in the sense of developer performance: Yes, TypeScript makes it easier to write accurate code more quickly and catch bugs prior to runtime.

Is TypeScript strong or weak typing? ›

In particular, TypeScript is strongly typed — that is, variables and other data structures can be declared to be of a specific type, like a string or a boolean, by the programmer, and TypeScript will check the validity of their values. This isn't possible in JavaScript, which is loosely typed.

Should I learn TypeScript or JavaScript 2023? ›

You may not find the one-size-fits-all answer to the question of which programming language is best for web development in 2023. However, if you are starting with learning to code or looking to build a more complex web application, TypeScript may be the better option.

Is TypeScript going to replace JavaScript? ›

TypeScript is not a replacement for JavaScript. TypeScript is simply a more feature-full and technically sound way to write JavaScript. To run an application written in TypeScript, the first step is to compile the code into JavaScript.

Do I need to learn react before TypeScript? ›

Do you really need to learn typescript as a React developer? In my personal experience, it's necessary to build React projects with TypeScript. Initially, it may feel like extra work to write types for each prop and value. However, in the long run, it helps a lot as your project grows.

What is disadvantage of TypeScript? ›

Disadvantages of TypeScript as compared to JavaScript

TS takes a long time to compile the code. TS doesn't support abstract classes. When using a third party library, there needs to be a definition file, and sometimes it's not always available. Quality of type definition files is a concern.

What is the easiest way to learn TypeScript? ›

10 Best Online Courses to learn TypeScript in 2023
  1. Understanding TypeScript — 2023 Edition. ...
  2. Typescript: The Complete Developer's Guide [2023] — Udemy. ...
  3. Typescript Masterclass & FREE E-Book. ...
  4. TypeScript for Professionals [Udemy] ...
  5. TypeScript Fundamentals [Pluralsight Best Course] ...
  6. Introduction to TypeScript Development.

What skills do you need for TypeScript? ›

Essential Skills for TypeScript Developers

Candidates must know other relevant programming languages, such as JavaScript, Java, PHP, and Ruby. They must be proficient with frameworks and libraries, especially with Angular and React.

How hard is it to go from JavaScript to TypeScript? ›

Migrating an application from JavaScript to TypeScript can be challenging and time-consuming, but it's never too late. TypeScript is a superset of JavaScript, so valid JavaScript code is a valid TypeScript code. Incremental migration, converting the whole project step by step is much more comfortable.

Is TypeScript worth the hype? ›

In this programmer's opinion, TypeScript is definitely worth learning. TypeScript is a great tool to improve your JavaScript code and has been an important contribution to writing better, enterprise-ready software. It produces fewer errors than JavaScript, is faster, and ideal for collaborating with other developers.

Is TypeScript more OOP than JavaScript? ›

Although TypeScript is a superset of JavaScript, object-oriented programming in TypeScript differs from Object-oriented programming in JavaScript because, unlike JavaScript, TypeScript has full class support, has access modifiers, and type annotations like most object-oriented programming languages.

Can TypeScript do everything JavaScript can? ›

Additional features

Compatibility: TypeScript supports virtually all JavaScript frameworks and libraries, including: React: A single-page application (SPA) that uses a virtual DOM to improve memory and performance. Vue: Written in TypeScript, easy to integrate into applications progressively.

Why use TypeScript not JavaScript? ›

TypeScript extends JavaScript, providing a better developer experience. The benefits of using TypeScript over JavaScript include: Static typing – TypeScript comes with optional static typing and a type inference system, which means that a variable, declared with no type may be inferred by TypeScript based on its value.

Why do people love TypeScript? ›

I am one of those programmers who wants to shorten their code to barely within readability and typescript seems like just adding extra code to fix a few bugs that can be fixed by better debugging without much effort.

Why developers love TypeScript every bit as much as Python? ›

Similarly to Python, JavaScript is compiled at runtime, meaning that you need to run the code to debug it. TypeScript, on the other hand, is compiled. This provides an extra layer of safety because programmers get information about possible bugs before execution time.

What language is TypeScript most similar to? ›

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.

What are the pros and cons of using TypeScript? ›

TypeScript vs JavaScript comparison
TypeScript
Code executionCompiled/transcompiled
Type systemStatic typing, strongly typed (optionally)
AdvantagesEasier to debug, quicker development
DisadvantagesMore initial setup, additional learning on top of JavaScript required
5 more rows
Sep 29, 2020

How widely used is TypeScript? ›

Only JavaScript has a larger number of primary language users. TypeScript was the fastest growing language in 2022, and has seen remarkable growth as a language over the past five years, rising from 12 percent usage in 2017 to 34 percent in 2022.

Is JavaScript going away? ›

JavaScript Is The Only Viable Option For Front-End Web Development. The main reason that JavaScript has never died, and likely will not die anytime soon, is because it's the best option we have for frontend development. There have been a lot of technologies that have done their best to replace JavaScript.

Why avoid any TypeScript? ›

any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.

Should I always use TypeScript? ›

In terms of software development, TypeScript offers many advantages over JavaScript: Optional static typing. JavaScript is a dynamically typed language, which means that types are checked, and data type errors are only detected at runtime. This can be very dangerous and can create errors during production.

Why is TypeScript the best programming language? ›

It is the best language for machine learning if you are utilizing TypeScript because it is a condensed version of JavaScript, making it simpler to comprehend and debug. It provides efficient JavaScript IDE development tools as well as other programming techniques. It becomes much easier to understand and read the code.

What is the best age to learn JavaScript? ›

Kids can start learning JavaScript as young as 8-10 years old. Coding truly is like learning a foreign language, and research has shown that younger kids are especially adept at learning new languages. Since JavaScript is a text-based language, typing skills are important to consider.

Is TypeScript an OOP language? ›

TypeScript on the other hand can be treated as an object-oriented language because of the language constructs it introduces on top of JavaScript closures. In this chapter, we will discuss each of the core concepts behind object-oriented ...

What is the advantage of TypeScript over JavaScript? ›

One of the main advantages of TypeScript over JavaScript is its improved tooling and integration with other technologies. TypeScript has a rich set of tools, such as an integrated development environment (IDE) and text editor support, that makes it easier to develop and debug code.

Do people still use TypeScript? ›

According to Stack Overflow's 2021 Developer Survey, TypeScript is about as popular as PYPL indicates it is, coming in as the seventh most popular language, as ranked by approximately 83,000 developers.

What will replace JavaScript in future? ›

While it is unlikely that JavaScript will be completely replaced by WebAssembly, it can be used to perform complex computations at near-native speeds, interact with other programming languages, and provide improved security and sandboxing.

What is replacing JavaScript? ›

If you are looking for an alternative for back-end development the most viable options could be Python, Ruby, Kotlin or PHP, for instance. If your purpose is front-end development, TypeScript, CoffeeScript, Elm, ClojureScript or Dart could be the better alternatives.

Is it worth it to use TypeScript with React? ›

React With Typescript Vs JavaScript: Performance

React with TypeScript offers faster performance than JavaScript because of its type system. TypeScript has static typing that helps the compiler make sure that the code is correct.

When should I start using TypeScript? ›

When it makes sense to use TypeScript
  1. When you have a large codebase. ...
  2. When your team's developers are already accustom to statically-typed languages. ...
  3. TypeScript can serve as a replacement for Babel. ...
  4. When a library or framework recommends TypeScript. ...
  5. When you really feel the need for speed.
Mar 24, 2016

Should I learn Angular or TypeScript first? ›

If you're working with Angular 2 — TypeScript is core to the framework, so it's strongly recommended to learn it before using Angular 2.

Does TypeScript make code faster? ›

TypeScript compiles down to JavaScript, meaning the TS code you write will be converted into JS before running. This provides faster execution times than JS since all the work is done ahead of time.

Why TypeScript is better than C#? ›

TypeScript is a popular choice for programmers accustomed to other languages with static typing, such as C# and Java. TypeScript's type system offers many of the same benefits, such as better code completion, earlier detection of errors, and clearer communication between parts of your program.

What are the three main simple types in TypeScript? ›

TypeScript Simple Types
  • boolean - true or false values.
  • number - whole numbers and floating point values.
  • string - text values like "TypeScript Rocks"

Is TypeScript needed to learn angular? ›

Angular is a modern framework built entirely in TypeScript, and as a result, using TypeScript with Angular provides a seamless experience. The Angular documentation not only supports TypeScript as a first-class citizen, but uses it as its primary language.

How many hours to master Angular? ›

If you are ready to spend at least 2-3 hours daily on learning Angular then around 2-3 months are sufficient. To grasp angular, we should know its core concepts first and few of them are listed below.

Is TypeScript really worth it? ›

In this programmer's opinion, TypeScript is definitely worth learning. TypeScript is a great tool to improve your JavaScript code and has been an important contribution to writing better, enterprise-ready software. It produces fewer errors than JavaScript, is faster, and ideal for collaborating with other developers.

How long does it take to master 10,000 hours? ›

Made popular by Gladwell's book, Outliers: The Story of Success, the principle states that in order to become world class in any field, you need 10,000 hours of deliberate practice. Article continues after video. This means 417 days' worth of hours, or 3 hours a day for 3,333 days--a little over 9 years.

Is it possible to learn Angular in a week? ›

It's just 3-courses you can take to learn Angular in 3-days or over a weekend. If you have no idea about Angular but you want to learn it to start your web development career then this should be the first course you should join.

Is Angular worth learning 2023? ›

Angular is a powerful JavaScript framework used to create dynamic web applications. It has been around since 2009 and has been gaining popularity ever since. In 2023, learning Angular will be even more beneficial as it will become the standard for developing modern web applications.

Is it OK to mix TypeScript and JavaScript? ›

Yes, you can use TypeScript and JavaScript together in the same project. TypeScript is a superset of JavaScript, which means that any valid JavaScript code is also valid TypeScript code.

Why TypeScript is so much better than JavaScript? ›

TypeScript vs JavaScript: Highlights

JavaScript is better suited for small-scale applications, while TypeScript is better for larger applications. TypeScript supports static typing but JavaScript does not. TypeScript supports interfaces but JavaScript does not.

Is TypeScript better for frontend or backend? ›

Using TypeScript On The Backend

For many organizations TypeScript is better suited than JavaScript for backend development because it's faster, produces fewer errors, leads to less debugging, and it's easier to collaborate within teams.

Videos

1. TypeScript Transformations with Pick and Omit
(Andrew Burgess)
2. Visual Studio Code Tutorial for Beginners | Learn Visual Studio Code in 1.5 Hour
(Getsitement)
3. How to Write JavaScript Documentation
(Jesse Weigel)
4. TypeScript Tutorial #10 - Function Signatures
(The Net Ninja)
5. Encrypted Notes App Tutorial for Beginners | React.JS + TypeScript
(Vincas Stonys)
6. IDE-like Refactors, Snippets, Tests, Hover Documentation, Commenting, and Git
(Semicolon & Sons)

References

Top Articles
Latest Posts
Article information

Author: Merrill Bechtelar CPA

Last Updated: 05/09/2023

Views: 5801

Rating: 5 / 5 (70 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Merrill Bechtelar CPA

Birthday: 1996-05-19

Address: Apt. 114 873 White Lodge, Libbyfurt, CA 93006

Phone: +5983010455207

Job: Legacy Representative

Hobby: Blacksmithing, Urban exploration, Sudoku, Slacklining, Creative writing, Community, Letterboxing

Introduction: My name is Merrill Bechtelar CPA, I am a clean, agreeable, glorious, magnificent, witty, enchanting, comfortable person who loves writing and wants to share my knowledge and understanding with you.