TypeScript 简介
什么是 TypeScript
TypeScript 是 JavaScript 的超集,可编译为纯 JavaScript。TypeScript 是纯面向对象的,具有类、接口和模块语句,就像 Java 或 C# 一样。
与 JavaScript 这种松散类型语言不同,TypeScript 支持静态类型。
一些优点
-
自文档化:无需在代码中添加注释,使用类型系统即可对代码进行注释,并且注释将始终与实际代码同步
-
避免常见的陷阱:TypeScript 会抛出任何编译错误,这与 JavaScript(解释型语言)不同。你可以在开发早期阶段捕获错误,从而减少 bug = 胜利
基本类型
const name: string = "Jane";
const age: number = 40;
const isAlive: boolean = true;
isAlive.indexOf("Jane"); // will show an error since indexOf cannot be called on a boolean
或者,这也行得通:
const name = "Jane";
const age = 40;
const isAlive = true;
isAlive.indexOf("Jane"); // will also throw an error
数组
let food: string[];
food = ["cookie", "milk", "biscuit"];
food.push("donut");
food = [1, 2, 3]; // will throw an error
food.push(true); // will also throw an error
功能
下面的函数接受一个字符串类型的参数(单词)并返回一个字符串。
function reverse(word: string): string {
return word
.split("")
.reverse()
.join("");
}
reverse("racecar"); // this is ok
reverse(true); // this will throw an error
我们可以省略返回类型,因为编译器可以推断出返回类型。因此,下面的代码也能正常工作:
function reverse(word: string) {
return word
.split("")
.reverse()
.join("");
}
接口
接口定义接口成员必须遵守的语法(例如属性、方法)。
接口仅包含成员的声明。定义成员是派生类的责任。
interface Person {
name: string;
age: number;
}
function birthYear(person: Person) {
return 2018 - person.age;
}
别名
类型别名为类型创建一个新名称。
type Vegetable = "broccoli" | "carrot";
// the '|' is a union type, which means that Vegetable can be either a 'broccoli' or 'carrot'
type Fruit = "apple" | "banana" | "kiwi";
type Ingredient = Vegetable | Fruit; // chaining union types
const juice: Ingredient[] = ["broccoli", "kiwi"];
// probably a terrible juice but still valid in TypeScript
const juice2: Ingredient[] = ["broccoli", "bread"];
// will throw an error since bread is not a fruit or vegetable
开始
- 安装 - 对于 NPM 用户:
npm install -g typescript
-
使用“.ts”扩展名命名文件。例如,“helloworld.ts”
-
编写代码
-
在命令行中输入以下命令来编译代码
tsc helloworld.ts
。如果一切顺利,将会生成一个 JavaScript 文件 helloworld.js!
React 应用程序中的 TypeScript
Create-React-App 现在内置了对使用 TypeScript 的支持!
要创建新项目,只需输入:
npx create-react-app my-typescript-app --typescript
要将 TypeScript 添加到现有应用程序:
npm install --save typescript @types/node @types/react @types/react-dom @types/jest
接下来,将任何文件重命名为 TypeScript 文件(例如将 src/index.js 重命名为 src/index.tsx)并重新启动开发服务器!
鏂囩珷鏉ユ簮锛�https://dev.to/delph/an-intro-to-typescript-1mb7