TypeScript(JavaScript 的一个超集)

TypeScript是一种由微软开发的开源的静态类型编程语言,它是JavaScript的一个超集,包含了JavaScript的所有语法特性,同时增加了一些新的特性和工具,如类型注解、接口、泛型等,可以用来编写大型、复杂的应用程序。

TypeScript的主要优点有:

  • 提前发现并修复错误:通过静态类型检查,可以在编译阶段就能发现代码中的错误,而不需要等到运行时。
  • 更好的可维护性:类型注解可以帮助开发者理解代码的功能和结构,提高代码的可读性和可维护性。
  • 支持面向对象编程:提供了类、接口、继承、泛型等面向对象的特性,使JavaScript更接近传统的面向对象语言。

TypeScript的使用方法主要包括以下几个步骤: 

  1. 安装TypeScript:可以使用npm命令进行安装,npm install -g typescript
  2. 创建TypeScript文件:创建一个.ts扩展名的文件,然后在其中编写TypeScript代码。
  3. 编译TypeScript:使用tsc命令进行编译,tsc filename.ts,会生成一个.js文件,这个文件就是编译后的JavaScript代码。

下面是一些基本的TypeScript示例: 

  • 类型注解:这是最基础也是最常见的TypeScript特性,它可以用来指定变量、函数参数和返回值的类型,帮助我们在编译阶段发现和修复错误。
let myName: string = "John Doe";
let myAge: number = 30;
let isStudent: boolean = true;

function greet(name: string): string {
  return "Hello, " + name;
}

console.log(greet(myName));
  • 接口:接口是一种定义对象形状的方法,它可以让我们的代码更加清晰和规范。我们可以使用接口来定义函数的输入输出,也可以用来定义类的实例应该有的属性和方法。
interface Person {
  firstName: string;
  lastName: string;
}

function printPerson(person: Person) {
  console.log(person.firstName + " " + person.lastName);
}

let user = {firstName: "John", lastName: "Doe"};
printPerson(user);
  • 泛型:泛型是一种让函数或类具有更多通用性的方法。我们可以使用泛型来编写可以处理多种类型的函数或类。 
function identity<T>(arg: T): T {
  return arg;
}

let output = identity<string>("myString");
console.log(output); // 输出"myString"
  • 枚举:枚举是一种特殊的类型,它可以用来表示一组常量。我们可以使用枚举来替代硬编码的数字或字符串,使得代码更加易于理解和维护。 
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
  • 函数重载:函数重载允许我们为同一个函数提供多个签名,每个签名都有自己的实现。这让我们可以在不改变函数名称的情况下提供多种功能。 
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
  if (typeof a === 'string' && typeof b === 'string') {
    return a + b;
  } else {
    return a + b;
  }
}

console.log(add(1, 2)); // 输出3
console.log(add('hello', 'world')); // 输出"helloworld"
  • 模块:模块是一个独立的代码单元,它可以有自己的导入和导出。使用模块可以更好地组织代码,避免全局变量污染,以及重复引入同一份代码的问题。
//undefined 导入模块
import * as math from './math';

// 使用模块
console.log(math.add(1, 2)); // 输出3
  • 装饰器:装饰器是一种特殊类型的声明,它可以被附加到类声明,方法,访问符,属性或参数上。装饰器使用@expression这种形式,expression求值后必须为一个函数,该函数会在运行时被调用,被装饰的声明信息做为参数传入。 
function log(target: Object, key: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;

  descriptor.value = function(...args: any[]) {
    console.log(`Calling "${key}" with`, args);
    return originalMethod.apply(this, args);
  };

  return descriptor;
}

class Math {
  @log
  add(a: number, b: number) {
    return a + b;
  }
}

const m = new Math();
m.add(1, 2); // 输出"Calling "add" with [1, 2]"
  • async/await:async/await是Promise的一种糖语法,它使得异步编程变得更加简洁和易于理解。
async function getData() {
  let response = await fetch('https://api.example.com/data');
  let data = await response.json();
  return data;
}

getData().then(data => console.log(data));
  • 类型断言:类型断言可以让编译器暂时忽略某个表达式的类型检查,从而让我们能够使用原本不允许使用的属性或方法。

let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length; // 类型断言为string
let strLength: number = (someValue as string).length; // 类型断言为string

console.log(strLength); // 输出"19"
  • never类型:never类型表示的是那些永不会出现的值。它通常是函数从未返回的结果或者是抛出异常。
function throwError(message: string): never {
  throw new Error(message);
}

let x: never = throwError("Something failed"); 
  • 可选参数和默认参数: 
function welcome(name?: string, greeting?: string) {
  if (!name) {
    name = "World";
  }

  if (!greeting) {
    greeting = "Hello";
  }

  console.log(`${greeting}, ${name}!`);
}

welcome(); // 输出"Hello, World!"
welcome("Alice"); // 输出"Hello, Alice!"
welcome("Bob", "Hi"); // 输出"Hi, Bob!"
  • 扩展类型(&): 
interface Square {
  kind: "square";
  size: number;
}

interface Circle {
  kind: "circle";
  radius: number;
}

type Shape = Square & Circle;

const shape: Shape = {
  kind: "circle",
  size: 10,
  radius: 5,
};

 对于嵌套多层且复杂的数据类型定义示例如下: 

假设有这样一组数据:

const userProfile = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA"
  },
  contactInfo: {
    phoneNumber: "+1-123-456-7890",
    emailAddress: "john.doe@example.com"
  }
};

1、使用接口(Interfaces)定义如下:

interface Address {
  street: string;
  city: string;
  country: string;
}

interface ContactInfo {
  phoneNumber: string;
  emailAddress: string;
}

interface UserProfile {
  name: string;
  age: number;
  address: Address;
  contactInfo: ContactInfo;
}

const userProfile: UserProfile = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA"
  },
  contactInfo: {
    phoneNumber: "+1-123-456-7890",
    emailAddress: "john.doe@example.com"
  }
};

 2、使用类型别名(Type Aliases)定义如下:

type Address = {
  street: string;
  city: string;
  country: string;
};

type ContactInfo = {
  phoneNumber: string;
  emailAddress: string;
};

type UserProfile = {
  name: string;
  age: number;
  address: Address;
  contactInfo: ContactInfo;
};

const userProfile: UserProfile = {
  name: "John Doe",
  age: 30,
  address: {
    street: "123 Main St",
    city: "New York",
    country: "USA"
  },
  contactInfo: {
    phoneNumber: "+1-123-456-7890",
    emailAddress: "john.doe@example.com"
  }
};

若有这样一组数据: 

const productList = [
  {
    name: "Product A",
    price: 10.99,
    stock: 10,
    comments: [
      { author: "Alice", content: "Great product!" },
      { author: "Bob", content: "I love it!" },
    ],
  },
  {
    name: "Product B",
    price: 19.99,
    stock: 5,
    comments: [
      { author: "Charlie", content: "Good quality." },
      { author: "David", content: "Fast delivery." },
    ],
  },
];

1、使用接口(Interfaces)定义: 

interface Comment {
  author: string;
  content: string;
}

interface Product {
  name: string;
  price: number;
  stock: number;
  comments: Comment[];
}

const productList: Product[] = [
  {
    name: "Product A",
    price: 10.99,
    stock: 10,
    comments: [
      { author: "Alice", content: "Great product!" },
      { author: "Bob", content: "I love it!" },
    ],
  },
  {
    name: "Product B",
    price: 19.99,
    stock: 5,
    comments: [
      { author: "Charlie", content: "Good quality." },
      { author: "David", content: "Fast delivery." },
    ],
  },
];

2、 使用类型别名(Type Aliases)定义:

type Comment = {
  author: string;
  content: string;
};

type Product = {
  name: string;
  price: number;
  stock: number;
  comments: Comment[];
};

const productList: Product[] = [
  {
    name: "Product A",
    price: 10.99,
    stock: 10,
    comments: [
      { author: "Alice", content: "Great product!" },
      { author: "Bob", content: "I love it!" },
    ],
  },
  {
    name: "Product B",
    price 19.99,
    stock: 5,
    comments: [
      { author: "Charlie", content: "Good quality." },
      { author: "David", content: "Fast delivery." },
    ],
  },
];

总结:   

通过以上特性,TypeScript 可以帮助开发者构建更稳定、更具扩展性的应用程序,并更好的开发体验。然而,它也有一些缺点,比如学习曲线较陡峭,需要额外的时间来理解和掌握。总的来说,TypeScript 是一种非常强大且实用的语言,特别适用于大规模的企业级应用和团队协作项目。 

  • 24
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值