TypeScript 入门
2024/3/15大约 3 分钟
TypeScript 入门
概述
TypeScript 是 JavaScript 的超集,添加了类型系统和其他特性。本文将介绍 TypeScript 的核心概念和使用方法。
1. 安装与配置
1.1 安装 TypeScript
# 全局安装
npm install -g typescript
# 项目安装
npm install typescript --save-dev
# 初始化配置
tsc --init1.2 tsconfig.json 配置
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"exclude": ["node_modules"]
}2. 基础类型
2.1 基本类型
// 字符串
let name: string = 'Blogger'
// 数字
let age: number = 30
// 布尔
let isActive: boolean = true
// 数组
let numbers: number[] = [1, 2, 3]
let strings: Array<string> = ['a', 'b', 'c']
// 元组
let tuple: [string, number] = ['hello', 10]
// 枚举
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Green
// 任意类型
let anyValue: any = 'hello'
anyValue = 123
// 空类型
let nothing: void = undefined
// 永不返回
function throwError(): never {
throw new Error('Error')
}2.2 类型推断
// TypeScript 会自动推断类型
let message = 'Hello' // 推断为 string
let count = 42 // 推断为 number
let isDone = false // 推断为 boolean3. 接口
3.1 基本接口
interface User {
id: number
name: string
age?: number // 可选属性
readonly email: string // 只读属性
}
const user: User = {
id: 1,
name: 'Blogger',
email: 'user@example.com'
}
// 类型断言
const anotherUser = {} as User
anotherUser.id = 23.2 接口继承
interface Person {
name: string
age: number
}
interface Employee extends Person {
employeeId: number
department: string
}
const employee: Employee = {
name: 'Blogger',
age: 30,
employeeId: 1001,
department: '技术部'
}3.3 函数接口
interface SearchFunc {
(source: string, subString: string): boolean
}
const search: SearchFunc = (source, subString) => {
return source.includes(subString)
}4. 类
4.1 基本类
class Person {
// 属性
name: string
private age: number // 私有属性
protected gender: string // 受保护属性
// 构造函数
constructor(name: string, age: number, gender: string) {
this.name = name
this.age = age
this.gender = gender
}
// 方法
greet(): string {
return `Hello, my name is ${this.name}`
}
// 获取器
getAge(): number {
return this.age
}
// 设置器
setAge(newAge: number): void {
if (newAge > 0) {
this.age = newAge
}
}
}
// 实例化
const person = new Person('Blogger', 30, '男')
console.log(person.greet())4.2 类继承
class Employee extends Person {
employeeId: number
constructor(name: string, age: number, gender: string, employeeId: number) {
super(name, age, gender) // 调用父类构造函数
this.employeeId = employeeId
}
work(): string {
return `${this.name} is working`
}
}
const employee = new Employee('Blogger', 30, '男', 1001)
console.log(employee.work())4.3 抽象类
abstract class Animal {
abstract makeSound(): void
move(): void {
console.log('Moving...')
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Woof!')
}
}
const dog = new Dog()
dog.makeSound() // Woof!
dog.move() // Moving...5. 泛型
5.1 泛型函数
function identity<T>(arg: T): T {
return arg
}
// 使用
const num = identity<number>(42)
const str = identity<string>('hello')
const arr = identity<number[]>([1, 2, 3])5.2 泛型类
class GenericNumber<T> {
zeroValue: T
add: (x: T, y: T) => T
constructor(zeroValue: T, addFn: (x: T, y: T) => T) {
this.zeroValue = zeroValue
this.add = addFn
}
}
const myNumber = new GenericNumber<number>(0, (x, y) => x + y)
console.log(myNumber.add(5, 3)) // 85.3 泛型约束
interface Lengthwise {
length: number
}
function logLength<T extends Lengthwise>(arg: T): T {
console.log(arg.length)
return arg
}
logLength('hello') // 5
logLength([1, 2, 3]) // 3
logLength({ length: 10, value: 'test' }) // 106. 类型守卫
6.1 typeof 类型守卫
function printValue(value: string | number) {
if (typeof value === 'string') {
console.log(value.toUpperCase())
} else {
console.log(value.toFixed(2))
}
}6.2 instanceof 类型守卫
class Bird {
fly() { console.log('Flying') }
}
class Fish {
swim() { console.log('Swimming') }
}
function move(animal: Bird | Fish) {
if (animal instanceof Bird) {
animal.fly()
} else {
animal.swim()
}
}6.3 自定义类型守卫
interface Dog {
bark(): void
}
interface Cat {
meow(): void
}
function isDog(pet: Dog | Cat): pet is Dog {
return (pet as Dog).bark !== undefined
}
function speak(pet: Dog | Cat) {
if (isDog(pet)) {
pet.bark()
} else {
pet.meow()
}
}7. 模块与命名空间
7.1 模块导入导出
// utils.ts
export function add(a: number, b: number): number {
return a + b
}
export const PI = 3.14159
export interface Point {
x: number
y: number
}
// main.ts
import { add, PI, Point } from './utils'
console.log(add(2, 3)) // 5
console.log(PI) // 3.14159
const point: Point = { x: 10, y: 20 }7.2 默认导出
// calculator.ts
export default class Calculator {
add(a: number, b: number): number {
return a + b
}
}
// main.ts
import Calculator from './calculator'
const calc = new Calculator()
console.log(calc.add(2, 3)) // 58. 实用类型
8.1 Partial
interface User {
id: number
name: string
email: string
}
// 所有属性变为可选
type PartialUser = Partial<User>
// { id?: number; name?: string; email?: string }8.2 Readonly
type ReadonlyUser = Readonly<User>
// { readonly id: number; readonly name: string; readonly email: string }8.3 Pick
type UserName = Pick<User, 'name' | 'email'>
// { name: string; email: string }8.4 Omit
type UserWithoutId = Omit<User, 'id'>
// { name: string; email: string }8.5 Record
type UserRecord = Record<string, User>
// { [key: string]: User }总结
TypeScript 提供了强大的类型系统,可以帮助开发者在编译时发现错误,提高代码质量和开发效率。
作者:Blogger
日期:2024年3月15日