There are two main ways to get the TypeScript tools:
- Via npm (the Node.js package manager)
- By installing TypeScript’s Visual Studio plugins
Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. If you didn’t install TypeScript with Visual Studio, you can still download it.
For NPM users:
Building your first TypeScript file
In your editor, type the following JavaScript code in
greeter.ts
:Compiling your code
We used a
.ts
extension, but this code is just JavaScript. You could have copy/pasted this straight out of an existing JavaScript app.
At the command line, run the TypeScript compiler:
The result will be a file
greeter.js
which contains the same JavaScript that you fed in. We’re up and running using TypeScript in our JavaScript app!
Now we can start taking advantage of some of the new tools TypeScript offers. Add a
: string
type annotation to the ‘person’ function argument as shown here:Type annotations
Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable. In this case, we intend the greeter function to be called with a single string parameter. We can try changing the call greeter to pass an array instead:
Re-compiling, you’ll now see an error:
Similarly, try removing all the arguments to the greeter call. TypeScript will let you know that you have called this function with an unexpected number of parameters. In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide.
Notice that although there were errors, the
greeter.js
file is still created. You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.Interfaces
Let’s develop our sample further. Here we use an interface that describes objects that have a firstName and lastName field. In TypeScript, two types are compatible if their internal structure is compatible. This allows us to implement an interface just by having the shape the interface requires, without an explicit
implements
clause.Classes
Finally, let’s extend the example one last time with classes. TypeScript supports new features in JavaScript, like support for class-based object-oriented programming.
Re-run
tsc greeter.ts
and you’ll see the generated JavaScript is the same as the earlier code. Classes in TypeScript are just a shorthand for the same prototype-based OO that is frequently used in JavaScript.Running your TypeScript web app
Now type the following in
greeter.html
:
Open
greeter.html
in the browser to run your first simple TypeScript web application!
1 comments:
I adore the way in which you write thanks for publishing. AZ-301 dumps
Post a Comment