TypeScript学习总结

TypeScript简介:
TypeScript 是一种由微软开发的自由和开源的编程语言。它是 JavaScript 的一个超集,可以编译成普通的JavaScript代码。TypeScript 最大的优势就是强类型约束和更好的编译时错误提示,这样有利于代码开发、维护和升级。

以下是我对 TypeScript 学习总结加上代码实例:

基础类型

// 布尔类型
let isDone: boolean = false;

// 数字类型
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;

// 字符串类型
let name: string = "Bob";
name = 'Smith';

// 数组类型
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];

// 元组类型
let x: [string, number];
x = ['hello', 10]; // OK
x = [10, 'hello']; // Error

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

// Any 类型
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; 

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

// Null 和 Undefined 类型
let u: undefined = undefined;
let n: null = null;

// Never 类型
function error(message: string): never {
    throw new Error(message);
}

function fail() {
    return error("Something failed");
}

function infiniteLoop(): never {
    while (true) {}
}

接口

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
  let newSquare = { color: "white", area: 100 };
  if (config.color) {
    newSquare.color = config.color;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let mySquare = createSquare({ color: "black" });

class Greeter {
    greeting: string;

    constructor(message: string) {
        this.greeting = message;
    }

    greet() {
        return "Hello, " + this.greeting;
    }
}

let greeter = new Greeter("world");

函数

// 命名函数
function add(x, y) {
    return x + y;
}

// 匿名函数
let myAdd = function(x, y) { return x + y; };

// 函数类型定义
function add(x: number, y: number): number {
    return x + y;
}

泛型

function identity<T>(arg: T): T {
    return arg;
}
  
let output1 = identity<string>("myString");  // type of output will be 'string'
let output2 = identity<number>(100);         // type of output will be 'number'

以上是 TypeScript 的一些基本语法和类型定义,从上面的代码示例可以看出 TypeScript 是一门强类型的语言,它可以提供更好的代码开发、维护和升级体验。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值