working on it ...

Filters

Explore Public Snippets

Sort by

Found 3,753 snippets matching: typescript

    public by micurs  6866142  356  9  18

    Typescript: passing a class member function as parameter to another function

    Typescript introduces the class construct and the concept of member functions. However if you try to pass a instance member function as parameter to another function the binding with the instance is lost. To solve this problem you can use the capability of javascript (and Typescript) to support closures on anonymous function (or lambda expressio
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    class SomePeople {
      values : string[] = [ 'John', 'Mary', 'Peter'];
    
      out() {
        _.each( this.values, (v) => process.stdout.write( v + '\n') );
      }
    }
    // This function accept a function it will execute internally
    function outSomething( outFunc : () => any ) {
      outFunc();
    }
    
    var crowd = new SomePeople();
    
    // This won't work since the actual crowd instance binding will be lost
    outSomething( crowd.out );
    
    // This will work: the closure within the lambda expression retain the
    // crowd instance and its data
    outSomething( () => crowd.out() );
        

    public by micurs  748071  19  7  0

    JQuery typescript interface for $.ajax() callbacks

    To use JQuery $.ajax() you must define your callback functions with the following interfaces
    interface OnSuccessAjaxCallback {
      (data: any, textStatus?: string, jqXHR?: JQueryXHR): any;
    }
    interface OnErrorAjaxCallback {
      (jqXHR?: JQueryXHR, textStatus?: string, errorThrow?: string) : any;
    }
    

    public by micurs  39066  458  10  8

    Using crypto-js in node.js with Typescript

    You can easily install the crypto-js library in node by using the command (on Mac): npm install crypto-js After that you need to download its type definition from Git/DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped/tree/master/cryptojs To make it work, however you need to add the following to the cryptojs.d.ts:
    // add this at the end of crypto.d.ts
      declare module "crypto-js" {
        export = CryptoJS;
      }
    
    // Then you can use the module in typescript
    
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/cryptojs.d.ts'/>
    
    import crypto = require("crypto-js");  
    
    function writeln( msg: string ) {
      process.stdout.write( msg +'\n');
    }
    
    var message : string = "Hello Encrypted World!";
    var cmessage : string = crypto.HmacSHA1( message , "1234").toString();
    writeln( message );
    writeln( cmessage );
    

    public by micurs  21540  97  9  4

    Using moment.js in node.js with Typescript

    You can easily install the moment.js library in node by using the command (on Mac): npm install moment After that you need to download its type definition from Git/DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped/tree/master/moment To make it work, however you need to add the following to the moment.d.ts :
    // add this at the end of moment.d.ts to export the moment symbol
    declare module "moment" { export = moment; } 
    
    // After that in your Typescript file you can use import
    import moment = require("moment");
    
       

    public by micurs  7708  4  9  11

    Typescript + underscore: iterating through a collection property of a class

    In this example we define a signature interface (Students) to locate a student using a student ID. In the Course class we use property getters function to provide read only access to the class members. Finally we use underscore to iterate on the Students as it was an array. The example runs on node.js with Typescript 0.9.5
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    function write(msg) {
        process.stdout.write(msg+'\n');
    }
    // Index Interface to locate a student given an id
    interface Students {
      [ studentId: number ] : Student;
    }
    
    class Student {
      private _id : number;
      private _name : string;
      private _lastName : string;
      constructor ( id: number, name : string, lastName : string ) {
        this._id = id;
        this._name = name;
        this._lastName = lastName;
      }
      // Property getters for Student
      get id() :number { return this._id; }
      get lastName() : string { return this._lastName; }
    }
    
    class Course {
      private title : string;
      _participants : Students = {};
    
      constructor( t : string ) {
        this.title = t;
      }
    
      addStudent( s: Student ) {
        this._participants[s.id] = s;
      }
      getStudent( sid: number ) : Student {
        return this._participants[sid];
      }
    
      // Property getter to retrieve the participants of a Course
      get participants() {
        return _.values(this._participants)    
      }
    
    }
    
    var c = new Course("Computer Science 101");
    c.addStudent(new Student(23,"Mark","Twain"));
    c.addStudent(new Student(100,"Albert","Einstein"));
    c.addStudent(new Student(120,"Isaac","Asimov"));
    
    _.each( c.participants , (s : Student) => write(s.lastName));
     

    public by micurs  12352  4  10  4

    Typescript + underscore: serializing objects

    This little example runs on node.js and assumes you have the typescript type-definition file in the types subdirectory. The example defines two classes one representing a undergrad course in computer science and another one representing possible students for the course. Few things are interesting here: 1 - the overloading of the toString()
    ///<reference path='../types/node.d.ts'/>
    ///<reference path='../types/underscore.d.ts'/>
    
    import _ = require("underscore");
    
    function write(msg) {
        process.stdout.write(msg+'\n');
    }
    
    class Student {
      firstName : string;
      lastName : string;
    
      constructor( n: string, v: string ) {
        this.firstName = n;
        this.lastName = v;
      }
    
      toString() : string {
        return '[ ' + this.firstName + ' ' + this.lastName + ' ]';
      }
    }
    
    class Class {
      title : string = "Computer Science 101";
      participants : Student[] = new Array();
    
      addStudent( s : Student ) : any {
        this.participants.push(s);
      }
    
      toString() : string {
        return this.title + '\n\t' 
              + _.reduce( this.participants, (acc,s) => acc += '\n\t'+ s );
      }
    
    }
    
    var firstSemesterClass : Class = new Class();
    
    firstSemesterClass.addStudent( new Student("John","Smith"));
    firstSemesterClass.addStudent( new Student("Frank","Gehry"));
    
    write( firstSemesterClass );
    
        

    public by teppeis  1308  1  4  0

    Mimimal code to compile TypeScript string (from https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API)

    Mimimal code to compile TypeScript string (from https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API): gistfile1.ts
    /// <reference path="typings/node/node.d.ts" />
    /// <reference path="typings/typescript/typescript.d.ts" />
    
    import ts = require("typescript");
    import fs = require("fs");
    import path = require("path");
    
    function transform(contents: string, libSource: string, compilerOptions: ts.CompilerOptions = {}) {
        // Generated outputs
        var outputs = [];
        // Create a compilerHost object to allow the compiler to read and write files
        var compilerHost = {
            getSourceFile: function (filename, languageVersion) {
                if (filename === "file.ts")
                    return ts.createSourceFile(filename, contents, compilerOptions.target, "0");
                if (filename === "lib.d.ts")
                    return ts.createSourceFile(filename, libSource, compilerOptions.target, "0");
                return undefined;
            },
            writeFile: function (name, text, writeByteOrderMark) {
                outputs.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
            },
            getDefaultLibFilename: function () { return "lib.d.ts"; },
            useCaseSensitiveFileNames: function () { return false; },
            getCanonicalFileName: function (filename) { return filename; },
            getCurrentDirectory: function () { return ""; },
            getNewLine: function () { return "\n"; }
        };
        // Create a program from inputs
        var program = ts.createProgram(["file.ts"], compilerOptions, compilerHost);
        // Query for early errors
        var errors = program.getDiagnostics();
        // Do not generate code in the presence of early errors
        if (!errors.length) {
            // Type check and get semantic errors
            var checker = program.getTypeChecker(true);
            errors = checker.getDiagnostics();
            // Generate output
            checker.emitFiles();
        }
        return {
            outputs: outputs,
            errors: errors.map(function (e) { return e.file.filename + "(" + e.file.getLineAndCharacterFromPosition(e.start).line + "): " + e.messageText; })
        };
    }
    
    // Calling our transform function using a simple TypeScript variable declarations, 
    // and loading the default library like:
    var source = "var x: number  = 'string'";
    var libSource = fs.readFileSync(path.join(path.dirname(require.resolve('typescript')), 'lib.d.ts')).toString();
    var result = transform(source, libSource);
    
    console.log(JSON.stringify(result));
    
    

    public by micurs  4304  1  7  3

    Defininig arrays using templates in Typescript

    You can now define an array using the template feature in Typescript. Be aware this way to build array is just a compile time 'type annotation' used to check type validity when using the array.
    class MyItemClass {
      ...
    }
    
    // Define an array for MyItemClass
    var itemArray : Array<MyItemClass>;
    ...
    
    var item : MyItem = itemArray[3];
    

    public by micurs  3842  2  7  3

    Generate comma separated value string in Typescript using underscore _.reduce()

    Underscore work well with Typescript lambda syntax.
    import _ = require("underscore");
    
    var values: number[] = [ 5, 19, 64, 12, 45 ];
    
    var csv: string = 
     _.reduce( values, 
              ( acc: string, item ) => acc+= ','+item.toString() 
             );
         

    public by micurs  2789  2  9  7

    Execute javascript code at the end of a CSS transition

    Using JQuery you can easily bind a function to any event. CSS transitions on a given element trigger different event depending on the browser. You can capture all or write a small function that select the one working on the current browser. Here is how (using typescript and underscore):
    function getBrowserTransitionEvent( el : JQuery ) : string {
      var transitions = [ 
        { name: 'transition', value: 'transitionend' },
        { name: 'OTransition', value: 'oTransitionEnd' },
        { name: 'MozTransition', value: 'transitionend' },
        { name: 'WebkitTransition', value: 'webkitTransitionEnd' } ];
      var HTMLElement e = el.get();
      var t = _.find< { name: string; value: string }>( transitions , 
          (t) => e.style[t.name] !== undefined);
      return t !== undefined ? t.value : '';
    }
    
    
    // Here is how to use this:
    $('#myElement').bind( getBrowserTransitionEvent($('#myElement')),
      function() {
        alert('CSS transision is complete');
      });
    • Public Snippets
    • Channels Snippets