[转]TypeScript Quick start

本文转自:http://www.typescriptlang.org/docs/tutorial.html

Quick start

Get started with a simple TypeScript app.

Let’s get started by building a simple web application with TypeScript.

Installing TypeScript

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 2015 and Visual Studio 2013 Update 2 include TypeScript by default. If you didn’t install TypeScript with Visual Studio, you can still download it.

For NPM users:

npm install -g typescript

Building your first TypeScript file

In your editor, type the following JavaScript code in greeter.ts:

function greeter(person) {
    return "Hello, " + person;
}

var user = "Jane User";

document.body.innerHTML = greeter(user);

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:

tsc greeter.ts

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:

function greeter(person: string) {
    return "Hello, " + person;
}

var user = "Jane User";

document.body.innerHTML = greeter(user);

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:

function greeter(person: string) {
    return "Hello, " + person;
}

var user = [0, 1, 2];

document.body.innerHTML = greeter(user);

Re-compiling, you’ll now see an error:

greeter.ts(7,26): Supplied parameters do not match any signature of call target

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.

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person: Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

var user = { firstName: "Jane", lastName: "User" };

document.body.innerHTML = greeter(user);

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.

Here we’re going to create a Student class with a constructor and a few public fields. Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction.

Also of note, the use of public on arguments to the constructor is a shorthand that allows us to automatically create properties with that name.

class Student {
    fullName: string;
    constructor(public firstName, public middleInitial, public lastName) {
        this.fullName = firstName + " " + middleInitial + " " + lastName;
    }
}

interface Person {
    firstName: string;
    lastName: string;
}

function greeter(person : Person) {
    return "Hello, " + person.firstName + " " + person.lastName;
}

var user = new Student("Jane", "M.", "User");

document.body.innerHTML = greeter(user);

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:

<!DOCTYPE html>
<html>
    <head><title>TypeScript Greeter</title></head>
    <body>
        <script src="greeter.js"></script>
    </body>
</html>

Open greeter.html in the browser to run your first simple TypeScript web application!

Optional: Open greeter.ts in Visual Studio, or copy the code into the TypeScript playground. You can hover over identifiers to see their types. Notice that in some cases these types are inferred automatically for you. Re-type the last line, and see completion lists and parameter help based on the types of the DOM elements. Put your cursor on the reference to the greeter function, and hit F12 to go to its definition. Notice, too, that you can right-click on a symbol and use refactoring to rename it.

The type information provided works together with the tools to work with JavaScript at application scale. For more examples of what’s possible in TypeScript, see the Samples section of the website.

时间: 2024-12-08 10:58:45

[转]TypeScript Quick start的相关文章

Getting started with TypeScript and Sublime Text -- 摘自https://cmatskas.com/getting-started-with-typescript-and-sublime-text/

Getting started with TypeScript and Sublime Text 04 March 2015  18 Comments  Posted in JavaScript, Open Source, TypeScript, Sublime Text UPDATED: This post has been rewritten around the official TypeScript plugin Typescript is awesome, period. TypeSc

[Algorithms] Quicksort algorithm using TypeScript

Quicksort (also called partition sort and pivot sort) is arguably the most used sorting algorithm. It is the one commonly implemented internally in language runtimes. In this lesson we cover the quick sort algorithm, why is it called quick and how to

Typescript : 遍历Array的方法:for, forEach, every等

方法一,for-of 这个貌似是最常用的方法,angular 2中HTML语法绑定也是要的这种语法. let someArray = [1, "string", false]; for (let entry of someArray) { console.log(entry); // 1, "string", false } for-in 官方文档上强调了for-in和for-of的区别: let list = [4, 5, 6]; for (let i in li

[TypeScript] Create random integers in a given range

Learn how to create random integers using JavaScript / TypeScript. /** * Returns a random int between * @param start inclusive * @param before exclusive */ export function randomInt(start: number, before: number) { return start + Math.floor(Math.rand

TypeScript+vsCode环境搭建

why? 1.基于前面文章的主观意见,所以个人倾向于将mvc的思想也使用到编程工具的使用上.工具嘛,无非是减少必要劳动力,提高工作效率的东西. 2.本人pc机上的vs2012自从装了resharper 之后,从启动速度上就慢了很多,启动一个项目要等待很长时间,且vs中对于ts的智能提示的速度让人难以忍受. start 0.本文是基于nodejs下进行的,没有配置好的同学请自行Google,非本文阐述内容. 1.github下载最新版TypeScript git clone https://git

TypeScript官方文档翻译-5

1.1 Ambient Declarations 1.1 环境声明 An ambient declaration introduces a variable into a TypeScript scope, but has zero impact on the emitted JavaScript program. Programmers can use ambient declarations to tell the TypeScript compiler that some other co

TypeScript系列1-1.5版本新特性

1. 简介 随着PC端快速向移动端迁移,移动(体验)优先的概念也越来越响.由于ReactJS目前移动端仅仅支持iOS,因此移动端Web开发框架只能选择: AngularJS/Angula2 + Ionic框架 + Cordova.想要学习好Angula2以及阅读其代码, 就必须了解和学习TypeScript,也因此需要学习好ES6以及Web Component.近期将开始学习TypeScript语言. 下面先看看TypeScript语言的发展: 鉴于JavaScript这种脚本语言很难应用于大规

【TypeScript】TypeScript 学习 5——方法

在 JavaScript 中,有两种方式定义方法. 1.命名的方法 function add(x,y){ return x+y; } 2.匿名方法 var myAdd = function(x,y) { return x+y;}; 在 TypeScript 中,也兼容上面两种定义方式,但是,既然我们用的是 TypeScript,那么肯定要强于本来的定义方式. 1.类型化方法 function add(x:number, y:number):number{ return x+y; } var my

Quick setup

Quick setup — if you’ve done this kind of thing before We recommend every repository include a README, LICENSE, and .gitignore. …or create a new repository on the command line echo "# Architect" >> README.md git init git add README.md git