TS-TypeScript学习_1

1、推断类型

const nameInfo: string = 'Hello world'

console.log('nameInfo', nameInfo)

2、定义类型

interface nameType {
  name: string;
  age: number;
}

const peopleInfo: nameType = {
  name: 'libai',
  age: 18
}

console.log('peopleInfo', peopleInfo)

 注:Type and Interface 的异同点

  • 相同点
    • 都可以用于描述函数、对象;都可以扩展
  • 不同点
    • Interface 可以使用 extends 和 implements(Type只能通过交叉类型实现 extends 行为)
      • interface IPeople { name: string }
        interface peopleInfo extends IPeople { age: number }
        let people: peopleInfo = { name: '李白', age: 18 }
      • type TPeople = { name: string }
        
        interface peopleInfo extends TPeople { age: number }

        let people: peopleInfo
        = { name: '李白', age: 18 }
      • type TPeople = { name: string }
        // type交叉类型
        type peopleInfo = TPeople & { age: number }
    • Interface 可以 声明合并 
      • interface peopleInfo = { name: string }
        
        interface peopleInfo = { age: number }
        
        let people: peopleInfo = { name: '李白', age: 18 }
    • Type 可以定义字符串字面量联合类型
      • type TPosition = 'left' | 'right' | 'top' | 'bottom'
        let positionInfo: TPosition = 'left' type TValue = string | number | boolean
        let numInfo: TValue
        = 18
    • Interface: 通过interface声明的接口,或者说声明的变量,它在声明的那一刻并不是最终类型,由于interface可以进行声明合并,所以它在创建后是可变的,可以将新成员添加到同一个interface中

    • Type: 类型别名不会创建类型,它只是创建了一个新名字来引用那个类型,其实就是一个对象字面量类型,所以类型别名一旦声明就无法更改它们

3、组合类型

  使用 TypeScript,你可以通过组合简单类型来创建复杂类型。有两种流行的方法可以做到这一点:联合和泛型。

  • 联合
    • 使用联合,你可以声明一个类型可以是多种类型之一。例如,你可以将 boolean 类型描述为 true 或 false。
      type MyBool = true | false
       type WindowStates = "open" | "closed" | "minimized"
        type LockStates = "locked" | "unlocked"
        type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9
  • 泛型
    • 泛型为类型提供变量。一个常见的例子是数组。没有泛型的数组可以包含任何东西。具有泛型的数组可以描述数组包含的值。
      • function peopleInfo<T>(value: T): T { return value }
        
        peopleInfo<number>(18)
        
        // 泛型传入 number 则 T 代表的数据类型 为 number
      • interface peopleInfo<T> {
            name: T,
            nameList: T[],
            handleName: (value: T) => void
        }
        
        const people: peopleInfo<string> = {
            name: '李白',
            nameList: [ '李白', '篱笆' ],
            handleName: (value: string) => { console.log(value) }
        }

        people.handleName('18')

        // 18 字符串
      • interface numInfo {
          length: number
        }
        
        function num<T extends numInfo>(value: T) {
          return value.length
        }
        
        console.log('num', num('18'))
        // 2
        
        console.log('num', num([{ a: 1}, { b: 2} ]))
        // 2
        
        console.log('num', num({ length: 5, b: '2', c: 3 }))
        // 5

4、更多学习内容:https://ts.nodejs.cn/docs/handbook/2/basic-types.html

posted on 2024-02-05 16:39  二两余晖  阅读(1)  评论(0编辑  收藏  举报