1. 环境搭建
1.1 安装配置
npm install -g typescript
tsc --init
1.2 基础配置文件
{
"compilerOptions" : {
"target" : "es5" ,
"module" : "commonjs" ,
"sourceMap" : true ,
"typeRoots" : [
"./typings" ,
"./node_modules/@types"
]
}
}
2. 基础语法入门
2.1 类型声明
let isDone: boolean = false ;
let count: number = 10 ;
let name: string = "TypeScript" ;
let list: number [ ] = [ 1 , 2 , 3 ] ;
let tuple: [ string , number ] = [ "hello" , 10 ] ;
let notSure: any = 4 ;
let u: undefined = undefined ;
let n: null = null ;
let v: void = undefined ;
let nv: never = ( ( ) => { throw new Error ( ) ; } ) ( ) ;
interface Person {
name: string ;
age? : number ;
readonly id: number ;
}
type StringOrNumber = string | number ;
let value: StringOrNumber = "hello" ;
value = 42 ;
type Direction = "North" | "South" | "East" | "West" ;
let dir: Direction = "North" ;
2.2 函数类型
function add ( x: number , y: number ) : number {
return x + y;
}
interface MathFunc {
( x: number , y: number ) : number ;
}
let multiply: MathFunc = ( x, y) => x * y;
function buildName ( firstName: string , lastName? : string ) : string ;
function buildName ( firstName: string , lastName = "Smith" ) : string {
return ` ${ firstName} ${ lastName} ` ;
}
function padding ( all: number ) ;
function padding ( topBottom: number , leftRight: number ) ;
function padding ( top: number , right: number , bottom: number , left: number ) ;
function padding ( a: number , b? : number , c? : number , d? : number ) {
}
2.3 类型断言和类型守卫
let someValue: any = "this is a string" ;
let strLength: number = ( someValue as string ) . length;
let strLength2: number = ( < string > someValue) . length;
function isString ( value: any ) : value is string {
return typeof value === "string" ;
}
function processValue ( value: string | number ) {
if ( isString ( value) ) {
console . log ( value. toUpperCase ( ) ) ;
} else {
console . log ( value. toFixed ( 2 ) ) ;
}
}
2.4 模块使用
import * as path from 'path' ;
import { parse } from 'path' ;
import myModule = require ( './mymodule' ) ;
export interface User {
name: string ;
age: number ;
}
2.5 泛型使用
class Repository< T > {
constructor ( private data: T [ ] ) { }
get ( id: number ) : T { ... }
}
function transform < T > ( items: any [ ] , mapper : ( item: any ) => T ) : T [ ] {
return items. map ( mapper) ;
}
3. 工程实践
3.1 与 JavaScript 互操作
类型声明文件(.d.ts)
declare module 'crypto-js' {
export function SHA256 ( message: string ) : string ;
}
安装第三方库类型定义
npm install jquery --save
npm install @types/jquery --save-dev
3.2 开发调试
VS Code 调试配置
{
"compilerOptions" : {
"sourceMap" : true ,
"outDir" : "./dist"
}
}
常用编译命令
命令 说明 tsc --watch
监听文件变化并实时编译 tsc --project tsconfig.json
使用指定配置编译
3.3 最佳实践
使用 strict
模式确保类型安全 优先使用接口(Interface)定义类型 合理使用类型推导,避免过度类型标注 保持良好的代码组织,遵循模块化原则
4. 常见问题解决
类型定义相关
检查 typeRoots
路径配置 确认是否安装了对应的 @types
包 检查 tsconfig.json
中的 noImplicitAny
设置
编译相关
确保 tsconfig.json
配置正确 使用 --watch
模式实时发现问题 查看生成的 sourceMap
定位问题
5. 高级使用技巧
5.1 条件类型
type TypeName< T > = T extends string
? "string"
: T extends number
? "number"
: T extends boolean
? "boolean"
: "object" ;
type ToArray< T > = T extends any ? T [ ] : never ;
type StrArrOrNumArr = ToArray< string | number > ;
type ReturnType< T > = T extends ( ... args: any [ ] ) => infer R ? R : any ;
type func = ( ) => number ;
type funcReturnType = ReturnType< func> ;
5.2 映射类型
type Readonly< T > = {
readonly [ P in keyof T ] : T [ P ] ;
} ;
type Partial< T > = {
[ P in keyof T ] ? : T [ P ] ;
} ;
type Record< K extends keyof any , T > = {
[ P in K ] : T ;
} ;
interface Todo {
title: string ;
description: string ;
}
type ReadonlyTodo = Readonly< Todo> ;
type PartialTodo = Partial< Todo> ;
type TodoRecord = Record< 'home' | 'work' , Todo> ;
5.3 装饰器使用
function classDecorator < T extends { new ( ... args: any [ ] ) : { } } > ( constructor: T ) {
return class extends constructor {
newProperty = "new property" ;
hello = "override" ;
} ;
}
function log ( target: any , propertyKey: string , descriptor: PropertyDescriptor) {
let originalMethod = descriptor. value;
descriptor. value = function ( ... args: any [ ] ) {
console . log ( ` Calling ${ propertyKey} with ` , args) ;
return originalMethod . apply ( this , args) ;
} ;
return descriptor;
}
@ classDecorator
class Example {
@ log
method ( arg: string ) {
return ` Method called with ${ arg} ` ;
}
}
5.4 高级类型工具
type UnionToIntersection< U > =
( U extends any ? ( k: U ) => void : never ) extends ( ( k: infer I ) => void ) ? I : never ;
type PropType< T , Path extends string > =
Path extends keyof T
? T [ Path]
: Path extends ` ${ infer K } . ${ infer R } `
? K extends keyof T
? PropType< T [ K ] , R >
: never
: never ;
type EventName< T extends string > = ` ${ T } Changed ` ;
type UserEvents = EventName< 'name' | 'age' > ;
参考资料