TypeScript 基本原理和使用方法,看这篇文章就够了

TypeScript 基本原理和使用方法

TypeScript 是 JavaScript 的一个超集,主要提供了类型系统和对 ES6+ 的支持。以下是 TypeScript 的基本原理和使用方法:

基本原理

  1. 静态类型检查

    • TypeScript 在编译时进行类型检查,而不是运行时
    • 可以提前发现潜在的类型错误
  2. 类型推断

    • 即使没有显式类型注解,TypeScript 也能根据上下文推断变量类型
  3. 渐进式类型系统

    • 可以逐步为 JavaScript 代码添加类型
    • 允许部分代码使用 any 类型绕过类型检查
  4. 编译过程

    • TypeScript 代码通过编译器 (tsc) 转换为 JavaScript 代码
    • 编译时会移除所有类型注解和接口等只在 TypeScript 中存在的特性

基本使用方法

1. 安装 TypeScript

bash 复制代码
npm install -g typescript

2. 初始化项目

bash 复制代码
tsc --init  # 创建 tsconfig.json 配置文件

3. 基本类型

typescript 复制代码
// 原始类型
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";

// 数组
let list: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // 泛型语法

// 元组
let tuple: [string, number] = ["hello", 10];

// 枚举
enum Color {Red, Green, Blue}
let c: Color = Color.Green;

// any
let notSure: any = 4;
notSure = "maybe a string instead";

// void
function warnUser(): void {
    console.log("This is a warning message");
}

// null 和 undefined
let u: undefined = undefined;
let n: null = null;

// never (表示永远不会返回的类型)
function error(message: string): never {
    throw new Error(message);
}

4. 接口

typescript 复制代码
interface Person {
    name: string;
    age?: number; // 可选属性
    readonly id: number; // 只读属性
    [propName: string]: any; // 任意属性
}

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

let tom: Person = {
    name: 'Tom',
    id: 1
};

5. 类

typescript 复制代码
class Animal {
    private name: string;
    
    constructor(name: string) {
        this.name = name;
    }
    
    move(distance: number = 0) {
        console.log(`${this.name} moved ${distance}m.`);
    }
}

class Dog extends Animal {
    constructor(name: string) {
        super(name);
    }
    
    bark() {
        console.log('Woof! Woof!');
    }
}

const dog = new Dog('Cooper');
dog.bark();
dog.move(10);

6. 泛型

typescript 复制代码
function identity<T>(arg: T): T {
    return arg;
}

let output = identity<string>("myString");
let output2 = identity("myString"); // 类型推断

interface GenericIdentityFn<T> {
    (arg: T): T;
}

let myIdentity: GenericIdentityFn<number> = identity;

7. 模块

typescript 复制代码
// math.ts
export function add(x: number, y: number): number {
    return x + y;
}

// app.ts
import { add } from './math';
console.log(add(2, 3));

8. 编译 TypeScript

bash 复制代码
tsc  # 编译所有 .ts 文件
tsc --watch  # 监听文件变化并自动编译

高级特性

  1. 类型别名

    typescript 复制代码
    type StringOrNumber = string | number;
  2. 联合类型和交叉类型

    typescript 复制代码
    let value: string | number;
    type Combined = Person & Employee;
  3. 装饰器

    typescript 复制代码
    @sealed
    class Greeter {
        greeting: string;
        
        constructor(message: string) {
            this.greeting = message;
        }
        
        @enumerable(false)
        greet() {
            return "Hello, " + this.greeting;
        }
    }
  4. 命名空间

    typescript 复制代码
    namespace Validation {
        export interface StringValidator {
            isAcceptable(s: string): boolean;
        }
    }

TypeScript 通过提供强大的类型系统,大大提高了 JavaScript 代码的可维护性和开发效率,同时保持了与现有 JavaScript 代码的兼容性。

PS:创作不易 学会了记得,点赞,评论,收藏,分享

相关推荐
IT码农-爱吃辣条3 小时前
Three.js 初级教程大全
开发语言·javascript·three.js
烛阴3 小时前
告别繁琐的类型注解:TypeScript 类型推断完全指南
前端·javascript·typescript
gnip3 小时前
工程项目中.env 文件原理
前端·javascript
JohnYan4 小时前
工作笔记 - CentOS7环境运行Bun应用
javascript·后端·容器
东风西巷6 小时前
Rubick:基于Electron的开源桌面效率工具箱
前端·javascript·electron·软件需求
Miracle_G7 小时前
每日一个知识点:JavaScript 箭头函数与普通函数比较
javascript
unfetteredman7 小时前
Error: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.32' not found
前端·javascript·vite
程序员小续8 小时前
React 官方严令禁止:Hook 不能写在 if/else,真相竟然是…
前端·javascript·程序员
小奋斗9 小时前
深入浅出:JavaScript中 三大异步编程方案以及应用
javascript·面试
尝尝你的优乐美9 小时前
封装那些Vue3.0中好用的指令
前端·javascript·vue.js