zoukankan      html  css  js  c++  java
  • TypeScript 之类型判断

    在使用 Angular 做项目的时候,对 TypeScript 的类型判断不太熟练,为了方便查找,特意对 TypeScript 的类型判断做了简单梳理。文章只是 TS 官网的内容摘要,没有高深的知识,想要深入学习 TS 还要看官网文档。

    基础类型

    // 布尔值
    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 list: number[] = [1, 2, 3];
    // 数组泛型
    let list: Array<number> = [1, 2, 3];
    
    //元组 Tuple
    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; // okay, definitely a boolean
    
    // Void
    function warnUser(): void {
        alert("This is my 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) {
        }
    }
    

    类型断言

    类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。

    let someValue: any = "this is a string";
    // “尖括号”语法
    let strLength: number = (<string>someValue).length;
    // as语法
    let strLength: number = (someValue as string).length;
    

    接口

    TypeScript 的核心原则之一是对值所具有的结构进行类型检查。 它有时被称做“鸭式辨型法”或“结构性子类型化”。 在 TypeScript 里,接口的作用就是为这些类型命名和为你的代码或第三方代码定义契约。

    interface LabelledValue {
      label: string;
    }
    
    // 可选属性
    interface SquareConfig {
      color?: string;
      width?: number;
    }
    
    // 只读属性
    interface Point {
        readonly x: number;
        readonly y: number;
    }
    
    // 函数类型
    interface SearchFunc {
      (source: string, subString: string): boolean;
    }
    
    // 可索引的类型
    interface StringArray {
      [index: number]: string;
    }
    
    // 类类型
    interface ClockInterface {
        currentTime: Date;
    }
    
    

    泛型

    我们把这个版本的 identity 函数叫做泛型,因为它可以适用于多个类型。 不同于使用 any,它不会丢失信息,像第一个例子那像保持准确性,传入数值类型并返回数值类型。

    function identity<T>(arg: T): T {
        return arg;
    }
    
  • 相关阅读:
    简单算法之插入排序(二)
    简单算法之选择排序(一)
    使用iptables为docker容器动态添加端口映射
    CentOS7出现Unit iptables.service could not be found
    linux系统下使用xampp 丢失mysql root密码【xampp的初始密码为空】
    centos6 安装docker
    Elasticsearch安装配置问题
    Elasticsearch技术解析与实战--shard&replica机制
    Elasticsearch聚合问题
    elasticsearch-head的使用
  • 原文地址:https://www.cnblogs.com/nzbin/p/9357247.html
Copyright © 2011-2022 走看看