TypeScript入门
搭建 TypeScript 开发环境
-
什么是 compiler?
-
less 编译器:
less
-
EcmaScript 6 编译器:
babel
-
TypeScript 编译器:
typescript
-
一句话:把 TypeScript 转换为 JavaScript ,浏览器就具有运行了
-
在线测试编译环境 compiler
-
本地开发编译环境
npm i -g typescript # 查看版本号 tsc --version # 查看使用帮助 tsc --help
编辑器的选择
-
Visual Studio Code
-
Sublime
-
Webstorm
-
...
Hello World
新建 greeter.ts
并写入以下内容:
function greeter(person) { return "Hello, " + person; } let user = "Jane User"; document.body.innerHTML = greeter(user);
安装编译器:
npm i -g typescript
编译:
tsc greeter.ts
function greeter(person: string) { return "Hello, " + person; } let user = "Jane User"; document.body.innerHTML = greeter(user);
重新编译执行。
function greeter(person: string) { return "Hello, " + person; } let user = [0, 1, 2]; document.body.innerHTML = greeter(user);
重新编译,你将看到如下错误:
error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
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: string, public middleInitial: string, public lastName: string) { this.fullName = firstName + " " + middleInitial + " " + lastName; } } // let user = new Student("Jane", "M.", "User");
console.log(user);