zoukankan      html  css  js  c++  java
  • TypeScript的概要和简介

    安装

    Typescript的基本介绍可以自行百度

    centos虚拟机中可以完整的体验, virtualbox安装开发版本,选择开发工具项,否则增强功能无法安装【提示kernel 头文件缺失,yum安装后仍是无效】

    一些具体的网址

    https://github.com/Microsoft/TypeScriptSamples

    http://www.typescriptlang.org/

    http://stackoverflow.com/questions/30536840/typescript-how-to-reference-jquery-easyui-library

    https://github.com/DefinitelyTyped/DefinitelyTyped

    由于typescript基于node的环境,因此需要安装nodejs npm ,然后安装依赖的包,

    直接链接国际站点太慢,加速npm包

    编辑 ~/.npmrc 加入下面内容

    registry = https://registry.npm.taobao.org

    sudo yum install nodejs

    sudo yum install npm

    npm install -g typescript

    如上即安装了typescript,命令行下输入tsc -h可以看看

    在Java项目中拥抱Nodejs — 使用gruntjs编译typescript,并将生成的js合并、压缩

    http://www.tuicool.com/articles/aY3IVz

    如果使用了idea专业版,直接集成了typescript,使用起来更简单,只要配置了项目文件就行,typescript的项目文件tsconfig.json类似如下,根据自己的需要设置即可

    {

       "compilerOptions": {

           "target": "es5",

           "noImplicitAny": false,

           "module": "commonjs",

           "removeComments": true,

           "sourceMap": true,

           "outDir": "js/dev/",

            "sourceRoot": "ts/"

        }

        //"include":[

        //     "ts"

        // ],

        //"exclude": [

        //     "js"

        // ]

    }

    基本类型

    //基本类型

    let flag: boolean = false;

    const pi = 3.1415;

    var n: number = 1;

    var s: string = 'hello';

    enum Color { Red, Green };

    var bns: number[] = [1, 2, 3];

    var ar: Array<number> = [1, 2]

    //any

    var list2 = [1, true, "free"];

    //

    var x = null;

    //union type

    var u: string | number;

    u = "OK";

    u = 42;

    //遍历

    for(b1 in bns){

        console.log(b1);

    }

    list2.forEach(e => {

        console.log(e);

    });

    //

    var tuple = { 'k1': 1, 'k2': (s: string): number => { console.log(s); return 100; } }

    console.log(tuple["k2"]("hello world"));

    interface IUserInfo {

        age: any;//定义一个任何变量的 age.

        userName: string;//定义一个 username.

        width?: number; //可选属性

    }

    //类和接口 默认作用域 public

    interface IClock {

        currentTime: Date;

        setTime(d: Date);

    }

    //--实现 IClock 接口

    class Clock implements IClock {

        currentTime: Date;

        //--构造函数方法

        constructor(h: number, m: number) {

            this.setTime(new Date());

        }

        setTime(d: Date) {

            this.currentTime = d;

        }

    }

    let clk = new Clock(10, 10);

    console.log(clk.currentTime);

    class Person {

        constructor(u: string) {

        }

    }

    class Student1 extends Person {

        constructor(username: string) {

            super(username);

        }

    }

    class Grid {

        static origin = { x: 0, y: 0 };//不需要实例化就能访问

        calculateDistanceFromOrigin(point: { x: number; y: number; }) {

            var xDist = (point.x - Grid.origin.x);

            var yDist = (point.y - Grid.origin.y);

            return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale;

        }

        constructor(public scale: number) { }

    }

    //.net语言的get set

    var passcode = "secret passcode";

    class Employee {

        private _fullName: string;

        get fullName(): string {

            return this._fullName;

        }

        set fullName(newName: string) {

            if (passcode && passcode == "secret passcode") {

                this._fullName = newName;

            } else {

                console.error("Error");

            }

        }

    }

    //定义合并

    interface Box {

        height: number;

        number;

    }

    interface Box {

        scale: number;

    }

    var box: Box = { height: 5, 6, scale: 10 }

    module Animals {

        export class Zebra { }

    }

    module Animals {

        export interface Legged { numberOfLegs: number; }

        export class Dog { }

    }

    var buildName1 = (firstName: string, lastName?: string) => {

        if (lastName) {

            return `${firstName} ${lastName}`;

        } else {

            return firstName;

        }

    };

    var b1 = buildName1("a", "b");

    console.log(n);

    function buildName(firstName: string, ...restOfName: string[]) {

        return `${firstName} ${restOfName.join(" ")}`;

    }

    var emplyeeName = buildName("lai", "xiao", "chai", "yun");

    console.log(emplyeeName);

    var deck = {

        suits: ["hearts", "spades", "clubs", "diamonds"],

        cards: Array(52),

        //要想在函数内使用“this”,内层使用箭头函数,外层使用正常函数

        createCardPicker: function () {

            return () => {

                var pickedCard = Math.floor(Math.random() * 52);

                var pickedSuit = Math.floor(pickedCard / 13);

                return { suit: this.suits[pickedSuit], card: pickedCard % 13 };

            }

        }

    }

    var cardPicker = deck.createCardPicker();

    var pickedCard = cardPicker();

    console.log(`card: ${pickedCard.card} of ${pickedCard.suit}`);

    function identity<T>(arg: T): T {

        return arg;

    }

    var output = identity<string>("string");

    console.log(output);

    class GenericNumber<T>{

        zeroValue: T;

        add: (x: T, y: T) => T;

        fuck(x) {

            return x + 1;

        }

    }

    var myGenericeNumber = new GenericNumber<number>();

    myGenericeNumber.zeroValue = 0;

    interface Lengthwise {

        length: number;

    }

    function logginIdentity<T extends Lengthwise>(arg: T): T {

        console.log(arg.length);

        return arg;

    }

    interface Fullname {

        [index: number]: string;

    }

    interface Firstname {

        [index: string]: string;

    }

    var myName: Fullname = ["lai", "chuanfeng"];

    var myFirstname: Firstname = { "firstname": "lai" };

    console.log(myName[0]);

    interface Account {

        add(x: number): void;

    }

    function account(): Account {

        return {

            add(x) { ++x }

        }

    }

    var a = account();

    a.add(5);

    //自动类型推导和提示

    function langsvr(){

        return {'a':'1', 'b':2};

    }

    langsvr().a;

    //自动的any类型

    var fn = (a, b) => { return a + b };

    console.log(fn(1, 2));

    console.log(fn("1", "2"));

    console.log(fn(1, "2"));

    定义

    和已有Javascript js交互的例子

    interface JQuery {
    text(content: string);
    }
    interface JQueryStatic {
    get(url: string, callback: (data: string) => any);
    (query: string): JQuery;
    }
    declare var $: JQueryStatic;
    $.get("http://mysite.org/divContent",
    function (data: string) {
    $("div").text(data);
    }
    );
    The 'JQueryStatic' interface references another interface: 'JQuery'. This interface represents a collection of one or more DOM elements.

    The jQuery library can perform many operations on such a collection, but in this example the jQuery client only needs to know that it can set the text content of each jQuery element in a collection by passing a string to the 'text' method.

    The 'JQueryStatic' interface also contains a method, 'get', that performs an Ajax get operation on the provided URL and arranges to invoke the provided callback upon receipt of a response.
    (query: string): JQuery;

    The bare signature indicates that instances of the interface are callable. This example illustrates that
    TypeScript function types are just special cases of TypeScript object types. Specifically, function types are object types that contain one or more call signatures.

    内置的Javascipt的类型支持
    declare var document;
    document.title = "Hello";
    // Ok because document has been declared
    In the case of 'document', the TypeScript compiler automatically supplies a declaration, because
    TypeScript by default includes a file 'lib.d.ts' that provides interface declarations for the built-in JavaScript  library as well as the Document Object Model

    typescript编译器内置的定义文件
    cancellationToken.js              lib.es2017.object.d.ts
    lib.dom.d.ts                      lib.es2017.sharedmemory.d.ts
    lib.dom.iterable.d.ts             lib.es5.d.ts
    lib.d.ts                          lib.es6.d.ts
    lib.es2015.collection.d.ts        lib.scripthost.d.ts
    lib.es2015.core.d.ts              lib.webworker.d.ts
    lib.es2015.d.ts                   protocol.d.ts
    lib.es2015.generator.d.ts         README.md
    lib.es2015.iterable.d.ts          tsc.js
    lib.es2015.promise.d.ts           tsserver.js
    lib.es2015.proxy.d.ts             tsserverlibrary.d.ts
    lib.es2015.reflect.d.ts           tsserverlibrary.js
    lib.es2015.symbol.d.ts            typescript.d.ts
    lib.es2015.symbol.wellknown.d.ts  typescript.js
    lib.es2016.array.include.d.ts     typescriptServices.d.ts
    lib.es2016.d.ts                   typescriptServices.js
    lib.es2017.d.ts                   typingsInstaller.js

  • 相关阅读:
    Servlet的生命周期?
    C++图结构的图结构操作示例
    如何从google play下载app应用,直接下载apk
    C# Socket异步聊天例子
    三极管饱和,放大,截止电压判断
    java中的浮点(float)运算
    微软2014校园招聘笔试试题
    软件开发中的资源控制问题学习
    linux mount命令学习
    17、Spring Boot普通类调用bean【从零开始学Spring Boot】
  • 原文地址:https://www.cnblogs.com/2018/p/6482445.html
Copyright © 2011-2022 走看看