0%

typescript 在前端开发中的应用

typescript 是什么?

typescript 是 JavaScript 的超集,由 Microsoft 开发。它添加了静态类型检查,让代码更健壮,易于维护。编译时会检查类型错误,减少运行时 bug。

为什么用 typescript?

  • 类型安全:提前发现错误
  • 更好的 IDE 支持:自动补全、重构
  • 代码可读性:类型注解像文档
  • 大型项目友好:团队协作更顺畅

安装和配置

1
npm install -g typescript

创建 tsconfig.json

1
2
3
4
5
6
7
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"strict": true
}
}

基本类型

1
2
3
4
let name: string = "小明";
let age: number = 25;
let isStudent: boolean = true;
let hobbies: string[] = ["阅读", "编程"];

接口和类型

1
2
3
4
5
6
7
8
interface Person {
name: string;
age: number;
}

function greet(person: Person) {
console.log(`你好,${person.name}!`);
}

类和继承

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Animal {
name: string;

constructor(name: string) {
this.name = name;
}

speak() {
console.log(`${this.name} 发出声音`);
}
}

class Dog extends Animal {
speak() {
console.log(`${this.name} 汪汪叫`);
}
}

泛型

让函数或类适用于多种类型。

1
2
3
4
5
function identity<T>(arg: T): T {
return arg;
}

let output = identity<string>("myString");

在 React 中使用

1
2
3
4
5
6
7
8
9
10
import React from 'react';

interface Props {
name: string;
age: number;
}

const Person: React.FC<Props> = ({ name, age }) => {
return <div>{name} 今年 {age} 岁</div>;
};

编译和运行

1
2
tsc main.ts  // 编译为 JS
node main.js // 运行

常见坑

  • 严格模式下不能用隐式 any
  • 接口 vs 类型别名
  • 可选属性用 ?

总结

typescript 学习曲线稍陡,但好处多。多写代码,熟悉类型系统。推荐用在大型项目或团队开发中。