TypeScript中的Hello World示例详细介绍

【TypeScript中的Hello World示例详细介绍】TypeScript是一种开源编程语言。它由Microsoft开发和维护。 TypeScript在语法上遵循javascript, 但向它添加了更多功能。它是一个超集的JavaScript。
下图描述了这种关系:

TypeScript中的Hello World示例详细介绍

文章图片
Typescript完全是面向对象的, 具有像Java这样的类, 对象和接口之类的功能。以前, 对于javascript变量和对象, 我们无需提及它们的数据类型, 这使整体逻辑难以理解, 因为我们不知道我们要处理的数据类型。 Typescript解决了此问题, 并为开发人员提供了一种声明变量和对象的数据类型的方法。
Typescript提供的一些内置类型是:
  1. 号码:整数和分数的64位双精度数字。
  2. 字串:字符或字符串类型数据的序列。
  3. 无效:用于不返回任何内容的函数。
  4. 空值 :表示无值或空值
  5. 布尔值:表示布尔值true或false
定义变量的语法:
var variable_name : type;

范例:
// declares a string type variable called name. var name: string; // declares a number type varibale called amount. var amount: number; // declares a boolean type variable called check; var checked: boolean; // declares a string type variable called first_name and // initializes with some value. var first_name: string = "lsbin" ; // declares an array of numbers called digits. var digits: number[];

定义类, 对象和函数的语法:
class Class_Name{ // instance variables // constructor // Typescript allows only one constructor per class constructor(parameters){ } // methods }var object_name:class_name; function_name(): returntype{ // function_body }

例子:
class Name { first_name: string; last_name: string; constructor(fname: string, lname: string) { first_name = fname; last_name = lname; } getName(): string { var fullname: string = first_name + last_name; return fullname; } }var author_name: Name;

运行Typescript代码
浏览器本机不了解Typescript, 但他们了解javascript。因此, 为了运行Typescript代码, 首先将其编译为javascript。
tsc:
是一个将Typescript代码转换成javascript的Typescript编译器(编译器)。
你可以通过运行以下命令来安装tsc:
npm install -g typescript

创建一个基本的Typescript代码, 以打印" Geeks For Geeks的问候":
var greet: string = "Greetings" ; var geeks: string = "Geeks For Geeks" ; console.log(greet + " from " + geeks); // save the file as hello.ts

要编译Typescript代码, 我们可以在命令行上运行以下命令:
tsc hello.ts

此命令将生成一个名称为hello.js的javascript文件
在命令行上使用以下命令运行javascript文件:
node hello.js

你应该在命令行上看到如下输出:
Greetings from Geeks For Geeks

TypeScript语言的应用:
  • Angular 2+版本是使用Typescript编写的, 并且使用Typescript, 这证明了它在工业用途中的效率。
  • Typescript使编译时错误诊断变得容易。
  • Typescript具有可伸缩性, 并很好地支持大型应用程序。
参考文献
1.
http://www.typescriptlang.org/
2.
http://www.typescriptlang.org/docs/index.html

    推荐阅读