前提:安装了node.js环境(新版本自带npm)
第一步:打开cmd,安装ts
npm install -g typescript
-g :代表全局安装
查看是否安装成功
tsc -v
第二步:在指定的目录下,使用记事本创建一个main.ts文件,在文件中输入如下代码
function greeter(person) {
return "Hello, " + person;
}
let user = "Jane User";
alert(greeter(user));
第三步:使用cmd,到达main.ts文件所在目录(win 使用cd)编译main.ts文件
tsc main.ts
编译成功之后就可以看到对应生成的main.js文件
第四步:在与main.js的相同目录下创建main.html文件
<html>
<head>
<meta charset="UTF-8">
<title>TS</title>
<script src="main.js"></script>
</head>
<body>
</body>
</head>
第五步:使用浏览器打开main.html,网页成功弹出Hello, Jane User
注意:
使用以下代码替换第二步的代码(包含接口和类的知识,与java类似),查看js文件和ts文件的代码区别
interface Person { /*接口*/
firstName: string;
lastName: string;
}
class Student { /*类*/
fullName: string; /*属性*/
constructor(public firstName, public lastName) { /*构造函数*/
this.fullName = firstName + " " + lastName;
}
sayHello(){ /*行为方法*/
console.log("Hello, (fullName)"+this.fullName);
}
}
function greeter(person : Person) { /*函数*/
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = new Student("Jane", "User"); /*创建实例*/
user.sayHello();
console.log(greeter(user));
编译ts文件后的js文件代码:
var Student = /** @class */ (function () {
function Student(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.fullName = firstName + " " + lastName;
}
Student.prototype.sayHello = function () {
console.log("Hello, (fullName)" + this.fullName);
};
return Student;
}());
function greeter(person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
var user = new Student("Jane", "User"); /*创建实例*/
user.sayHello();
console.log(greeter(user));