TypeScript基礎

TypeScript能夠編譯出純淨、 簡潔的JavaScript代碼,而且能夠運行在任何瀏覽器上、Node.js環境中和任何支持ECMAScript 3(或更高版本)的JavaScript引擎中。下面咱們將從最基礎的瞭解typescript。react

  • 安裝typescript
    yarn global add typescript
  • 咱們先從類型,接口,類簡單的舉一個例子看看他們。
    一、類型
    const foo = (x:string,y:number) => {
        console.log(x)
    }
    foo("s",2)
    //編譯成es5
    var foo = function (x, y) { console.log(x); }; foo("s", 2);

    二、接口typescript

    interface Foo {
        name: string;
        age: number;
    }//接口類型的定義
    const child = (x:Foo) => {
        console.log(x.name+","+x.age)
    }
    child({ name: "hou", age: 12 })
    
    //編譯成es5
    var child = function (x) {
        console.log(x.name + "," + x.age);
    };
    child({ name: "hou", age: 12 });

    三、類瀏覽器

    interface Foo {
        name: string;
        age: number;
    }
    class Fzz implements Foo { //實現接口
        name: string;
        age: number;
        constructor(n:string) {
            this.name = n
        }
        sayName() {
            return this.name
        }
    }
    const fzz = new Fzz("hou") //實例化類,react自動給你實例化了
    fzz.sayName()
    
    //編譯成es5
    var Fzz = /** @class */ (function () {
        function Fzz(n) {
            this.name = n;
        }
        Fzz.prototype.sayName = function () {
            return this.name;
        };
        return Fzz;
    }());
    var fzz = new Fzz("hou");
    fzz.sayName();
相關文章
相關標籤/搜索