Ready
2019-10-16 本文已影响0人
竹林_
构建第一个TypeScript文件
安装TypeScript
npm install -g typescript
// TypeScript放到以.ts结尾的文件中,其中参数person:string为类型注释
// greeter.ts
function greeter(person: string) {
return "Hello, " + person;
}
let user = "Jane User";
document.body.innerHTML = greeter(user);
编译代码
tsc greeter.ts
执行完上面命令行以后会生成一个相同名称并且以.js结尾的文件,引入js文件到HTML中就可以正常运行
// 执行完tsc greeter.ts以后生成js文件内容
function greeter(person) {
return "Hello, " + person;
}
var user = "World";
document.body.innerHTML = greeter(user);
接口
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = { firstName: "Jane", lastName: "User" };
document.body.innerHTML = greeter(user);
类
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;
}
let user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
项目介绍
tsconfig.json简单配置TS项目额外的需要一个tsconfig.json文件对TS进行配置,具体配置下图:
详细compilerOptions配置
webpack配置webpack配置:
项目目录简单的项目目录