1.1 TypeScript 安装与调试

安装

npm install [email protected] -g
npm install [email protected] -g

调试

  1. 安装 vscode,command + K、command + S 自定义格式化按键

  2. 创建 ts 文件

  3. 在目录下新建 /.vscode/launch.json,这样 vscode 就可以用 ts-node 调试了

     {
         "configurations": [
             {
             "name": "ts-node",
             "type": "node",
             "request": "launch",
             "program": "/usr/local/bin/ts-node",
             "args": ["${relativeFile}"],
             "cwd": "${workspaceRoot}",
             "protocol": "inspector"
             }
         ]
     }
    

官方 5 分钟文档

  1. 函数可以添加类型注解

    function greeter(person: string) {
        return 'Hello, ' + person
    }
    
    let user = 'Dolores_2B'
    
    console.log(greeter(user))
    
  • 注意:如果传的是非 string 类型,编译时会报错
  • 如果传的是 undefined,编译也会通过
  1. 接口

    interface Person {
        firstName: string
        lastName: string
    }
    
    function greeter(person: Person) {
        return 'Hello, ' + person.firstName + ' ' + person.lastName
    }
    
    let user = {
        firstName: 'Dolores',
        lastName: '2B'
    }
    console.log(greeter(user))
    
    enum Gender {
        Male,
        Female
    }
    
    interface Person {
        gender: Gender
    }
    
    function merry(a: Person, b: Person): [Person, Person] {
        if (a.gender !== b.gender) {
            return [a, b]
        }else {
            throw new Error('性别相同不能结婚')
        }
    }
    
    let a = {
        gender: Gender.Male
    }
    let b = {
        gender: Gender.Male
    }
    console.log(merry(a, b))
    
  2. 函数的重载

    function add(a: string, b: string)
    function add(a: number, b: number)
    function add(a: any, b: any): any {
        return a + b
    }
    console.log(add('Dolores', 1))
    

你可能感兴趣的:(1.1 TypeScript 安装与调试)