zoukankan      html  css  js  c++  java
  • 5分钟上手TypeScript

    安装TypeScript

    安装这个工具有两种方式:

    • 用npm安装npm install -g typescript
    • 安装visual studio的TypeScript插件

    编译TypeScript

    用TypeScript写的文件的后缀名是.ts,需要使用tsc 文件名.ts来编译成JavaScript文件,运行tsc test.ts命令会在当前目录下创建一个同名的JavaScript文件

    类型注解

    TypeScript的类型注解是一种轻量级的为函数和变量添加约束的方式。

    //这里限制person是一个字符串
    function greeter(person: string) {
        return "Hello, " + person;
    }
    
    let user = ‘fff’;
    
    document.body.innerHTML = greeter(user);
    

    接口

    //这里定义了包含firstName和lastName两个字段的Person接口
    interface Person{
        firstName:string,
        lastName:string
    }
    const person1 = {
        firstName:'tom',
        lastName:'jedt'
    };
    //但是在使用的时候,没有像java还需要使用implements语句,直接使用Person即可。
    function consolePerson(person:Person){
        return person.firstName+person.lastName;
    }
    console.log(consolePerson(person1));
    

    只要两个类型在内部的结构是兼容的,那么这两个类型就是兼容的,如上面的例子,在使用Person的时候,保证了person1是一个对象,而且内部的两个字段都是字符串类型的。

    TypeScript支持JavaScript的新特性,如基于类的面向对象编程

    class Student{
        fullName:string;
        constructor(public firstName,public middleName,public lastName){
            this.fullName = firstName + " " + middleName + " " + lastName;
        };
        public getFullName(){
            return this.fullName;
        }
    }
    
    interface OnePerson{
        firstName:string,
        lastName:string
    }
    
    function showPerson(person:OnePerson,fullName:Function){
        return person.firstName + person.lastName + fullName;
    }
    const xiao = new Student("top1","ttt","sportswell");
    console.log(showPerson(xiao,xiao.getFullName));
    

    类和接口可以一起使用,特别好用的是TypeScript的类型注解。

  • 相关阅读:
    python直接赋值、浅拷贝与深拷贝的区别解析
    join shuffle
    Python工作流-Airflow
    【JAVA基础语法】(一)Arrays.asList的使用
    Java中的数组和List
    ArrayList和LinkedList区别
    Array和ArrayList区别
    iOS项目崩溃日志采集与分析
    iOS超全开源框架、项目和学习资料汇总
    iOS webView、WKWebView、AFNetworking 中的cookie存取
  • 原文地址:https://www.cnblogs.com/sminocence/p/9024784.html
Copyright © 2011-2022 走看看