zoukankan      html  css  js  c++  java
  • TypeScript

    typeScript是JavaScript类型的超集,它可以编译成纯JavaScript,typeScript可以在任何浏览器、任何计算机和任何操作系统上运行

    1.两种方式来获取typeScript工具

    1. 通过npm安装
      npm install -g typescript
    2. 安装Visual Studio的TypeScript插件 

    TypeScript中使用:指定变量类型,:前后有没有空格都可以

    const variableName: string = '啦啦啦'

    在TypeScript中可以使用void表示没有返回值的函数

    function alertName(): void {
      console.log('啦啦啦啦');
    }

    如果想声明一个void的变量,它只能赋值为undefined和null

    let unusable: void = undefined;

    任意值(any)用来表示允许赋值为任意类型,在任意值上访问任何属性都是允许的

    变量如果在声明的时候,未指定其类型,那么它会被识别为任意值类型

    let anyName: any = 'xtddx'
    anyName = 0
    console.log(anyName.aa)
    
    let noneName
    noneName = 'aksbdkas'
    noneName = 0

    类型推论:如果没有明确的指定类型,那么TypeScript会按照类型推论的规则推断一个类型(如果定义的时候没有复制则会被推断为any类型而完全不被类型检查)

    联合类型:表示取值可以为多种类型中的一种,多个类型使用 | 分隔多个类型,

    当不确定联合类型的变量具体是哪个类型的时候只能访问定义的多个类型的公共属性

    联合变量在被赋值的时候会根据类型推论推断出一个类型

    let jointName: number | string
    // Property 'length' does not exist on type 'string | number'.
    // Property 'length' does not exist on type 'number'.
    // jointName.length  // 调用length方法时报错
    jointName.toString()
    jointName = 'skjd'
    console.log(jointName.length)
    jointName = 0
    // Property 'length' does not exist on type 'number'
    // console.log(jointName.length) //报错

     索引签名:TypeScript支持两种索引签名:字符串和数字

    interface Person { // 定义Person接口
      name: string; // 接口的确定属性,且类型是string
      age?: number; // 接口的可选属性,且类型是number
      [propName: number]: any; // 任意属性,[propName:string]定义了任意属性取string类型,any定义了任意属性值取any类型
    }
    
    let tom: Person = {
      name: '名字',
      3: 'aa'
    }
    
    interface Person2 { // 定义Person接口
      name: string; // 接口的确定属性,且类型是string
      age?: number; // 接口的可选属性,且类型是number
      [propName: string]: any; // 任意属性,[propName:string]定义了任意属性取string类型,any定义了任意属性值取any类型
    }
    
    let tom2: Person2 = {
      name: '名字',
      aaa: 'aa'
    }

     https://ts.xcatliu.com/basics/type-of-object-interfaces

  • 相关阅读:
    二分与三分
    NOIP应试技巧
    数论
    并差集
    最短路
    图的遍历

    最小生成树
    树状数组
    线段树
  • 原文地址:https://www.cnblogs.com/wangxirui/p/11927906.html
Copyright © 2011-2022 走看看