Global stocks sank Wednesday after US President Donald Trump said he was not satisfied with talks that are aimed at averting a trade war with China. Equities were also dented by poor eurozone economic data, and as Trump cast doubt on a planned summit with North Korean leader Kim Jong Un. “Trump (is) continuing to drive uncertainty over global trade,” said analyst Joshua Mahony at trading firm IG. “European markets are following their Asian counterparts lower, as a pessimistic tone from Trump is compounded by downbeat economic data,” he added. Markets had surged Monday after US Treasury Secretary Steven Mnuchin and Chinese Vice Premier Liu He said they had agreed to pull back from imposing threatened tariffs on billions of dollars of goods, and continue talks on a variety of trade issues. However, Trump has declared that he was “not satisfied” with the status of the talks, fuelling worries that the world’s top two economies could still slug out an economically pain...
Microsoft introduced TypeScript, a typed superset for JavaScript that compiles into plain JavaScript. TypeScript focuses on providing useful tools for large scale applications by implementing features, such as classes, type annotations, inheritance, modules and much more! In this tutorial, we will get started with TypeScript, using simple bite-sized code examples, compiling them into JavaScript, and viewing the instant results in a browser.
Installing the Tools
TypeScript features are enforced only at compile-time.
You'll set up your machine according to your specific platform and needs. Windows and Visual Studio users can simply download the Visual Studio Plugin. If you're on Windows and don't have Visual Studio, give Visual Studio Express for Web a try. The TypeScript experience in Visual Studio is currently superior to other code editors.
If you're on a different platform (or don't want to use Visual Studio), all you need is a text editor, a browser, and the TypeScript npm package to use TypeScript. Follow these installation instructions:
- Install Node Package Manager (npm)
- Install the TypeScript npm package globally in the command line:12345
$ npm
install
-g typescript
$ npm view typescript version
npm http GET https:
//registry
.npmjs.org
/typescript
npm http 304 https:
//registry
.npmjs.org
/typescript
0.8.1-1
- Any modern browser: Chrome is used for this tutorial
- Any text editor: Sublime Text is used for this tutorial
- Syntax highlighting plugin for text editors
That's it; we are ready to make a simple "Hello World" application in TypeScript!
Hello World in TypeScript
TypeScript is a superset of Ecmascript 5 (ES5) and incorporates features proposed for ES6. Because of this, any JavaScript program is already a TypeScript program. The TypeScript compiler performs local file transformations on TypeScript programs. Hence, the final JavaScript output closely matches the TypeScript input.
First, we will create a basic
index.html
file and reference an external script file:
01
02
03
04
05
06
07
08
09
10
11
12
| <! doctype html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >Learning TypeScript</ title > </ head > < body > < script src = "hello.js" ></ script > </ body > </ html > |
This is a simple "Hello World" application; so, let's create a file named
hello.ts
. The *.ts
extension designates a TypeScript file. Add the following code to hello.ts
:
1
| alert( 'hello world in TypeScript!' ); |
Next, open the command line interface, navigate to the folder containing
hello.ts
, and execute the TypeScript compiler with the following command:
1
| tsc hello.ts |
The
tsc
command is the TypeScript compiler, and it immediately generates a new file called hello.js
. Our TypeScript application does not use any TypeScript-specific syntax, so we see the same exact JavaScript code in hello.js
that we wrote in hello.ts
.
Great! Now we can explore TypeScript's features and see how it can help us maintain and author large scale JavaScript applications.
Type Annotations
Type annotations are an optional feature, which allows us to check and express our intent in the programs we write. Let's create a simple
area()
function in a new TypeScript file, called type.ts
1
2
3
4
5
6
| function area(shape: string, width: number, height: number) { var area = width * height; return "I'm a " + shape + " with an area of " + area + " cm squared." ; } document.body.innerHTML = area( "rectangle" , 30, 15); |
Next, change the script source in
index.html
to type.js
and run the TypeScript compiler with tsc type.ts
. Refresh the page in the browser, and you should see the following:
As shown in the previous code, the type annotations are expressed as part of the function parameters; they indicate what types of values you can pass to the function. For example, the
shape
parameter is designated as a string value, and width
and height
are numeric values.
Type annotations, and other TypeScript features, are enforced only at compile-time. If you pass any other types of values to these parameters, the compiler will give you a compile-time error. This behavior is extremely helpful while building large-scale applications. For example, let's purposely pass a string value for the
width
parameter:
1
2
3
4
5
6
| function area(shape: string, width: number, height: number) { var area = width * height; return "I'm a " + shape + " with an area of " + area + " cm squared." ; } document.body.innerHTML = area( "rectangle" , "width" , 15); // wrong width type |
We know this results in an undesirable outcome, and compiling the file alerts us to the problem with the following error:
1
2
| $ tsc type .ts type .ts(6,26): Supplied parameters do not match any signature of call target |
Notice that despite this error, the compiler generated the
type.js
file. The error doesn't stop the TypeScript compiler from generating the corresponding JavaScript, but the compiler does warn us of potential issues. We intend width
to be a number; passing anything else results in undesired behavior in our code. Other type annotations include bool
or even any
.Interfaces
Let's expand our example to include an interface that further describes a shape as an object with an optional
color
property. Create a new file called interface.ts
, and modify the script source in index.html
to include interface.js
. Type the following code into interface.ts
:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
| interface Shape { name: string; width: number; height: number; color?: string; } function area(shape : Shape) { var area = shape.width * shape.height; return "I'm " + shape.name + " with area " + area + " cm squared" ; } console.log( area( {name: "rectangle" , width: 30, height: 15} ) ); console.log( area( {name: "square" , width: 30, height: 30, color: "blue" } ) ); |
Interfaces are names given to object types. Not only can we declare an interface, but we can also use it as a type annotation.
Compiling
interface.js
results in no errors. To evoke an error, let's append another line of code to interface.js
with a shape that has no name property and view the result in the console of the browser. Append this line to interface.js
:
1
| console.log( area( {width: 30, height: 15} ) ); |
Now, compile the code with
tsc interface.js
. You'll receive an error, but don't worry about that right now. Refresh your browser and look at the console. You'll see something similar to the following screenshot:
Now let's look at the error. It is:
1
2
| interface.ts(26,13): Supplied parameters do not match any signature of call target: Could not apply type 'Shape' to argument 1, which is of type '{ width: number; height: number; }' |
We see this error because the object passed to
area()
does not conform to the Shape
interface; it needs a name property in order to do so.Arrow Function Expressions
Understanding the scope of the
this
keyword is challenging, and TypeScript makes it a little easier by supporting arrow function expressions, a new feature being discussed for ECMAScript 6. Arrow functions preserve the value of this
, making it much easier to write and use callback functions. Consider the following code:
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
| var shape = { name: "rectangle" , popup: function () { console.log( 'This inside popup(): ' + this .name); setTimeout( function () { console.log( 'This inside setTimeout(): ' + this .name); console.log( "I'm a " + this .name + "!" ); }, 3000); } }; shape.popup(); |
The
this.name
on line seven will clearly be empty, as demonstrated in the browser console:
Comments
Post a Comment