Sunday, January 13, 2013

Extension methods in TypeScript

/* 18/1 2013Update Remember Extension methods are code smell, so use it only where it really make sense.
Good blog post about Extension methods why its code smell http://www.daedtech.com/why-i-dont-like-c-extension-methods   
*/

When working with strings it’s likely that you’ve had to check if the string is null or empty, and
Thats no different in TypeScript.

I thougt of making an extension method for StringIsNullOrEmpty, but could not fine any documentation on this.

I know that TypeScript interfaces are open ended, so I extended the String interface like this

    interface String {
        StringIsNullOrEmpty: () => bool;
    }


Then I just need to found out how to inplement it, and used prototype for this.

    String.prototype.StringIsNullOrEmpty = () : bool{
        return this == null || this.length == 0;
    }


This works fine, but I'm not sure this is the correct way of doing this, so if you know a better way please leave a comment.

I have encapsulated the inteface and all my prototypes into a module called StringExtensions

module StringExtensions {
    interface String {
        StringIsNullOrEmpty: () => bool;
    }

    String.prototype.StringIsNullOrEmpty = () : bool{
        return this == null || this.length == 0;
    }
}


Here is a litle jasmine test.

describe("StringExtensions methods tests", () => {

    it("Given an empty string should return true", () => {

        // Fixture setup       

        var sut = "";

        // Exercise system               

        var expected = true;

        // Verify outcome

        expect(sut.StringIsNullOrEmpty()).toEqual(expected);

        // Teardown

    });   
});

35 comments:

  1. i have also this functions:

    interface String {
    formatWith(...args: string[]): string;
    formatWith(...args: any[]): string;
    }

    and JS part:

    String.prototype.formatWith = function () {
    var params = $.makeArray(arguments);
    return $.validator.format(this, params);
    };

    ReplyDelete
  2. I tested your method but it fails when string variable is null, it throws:
    Cannot call method 'StringIsNullOrEmpty' of null. I think this cannot be implemented in JS.

    ReplyDelete
    Replies
    1. Hi Peter,

      Thanks for the comment, maybe something has change since I wrote this post. I will try play with extension methods in typescript again :-)

      Delete
  3. Seems wrap the extension methods in a module doesn't work in angular cli environment.

    ReplyDelete
  4. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from TypeScript Training in Chennai . or learn thru Javascript Online Training from India. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete
  5. GREAT topic! It is really interesting to read from the beginning & I would like to share your blog to my circles, keep sharing… DevOps Online Training
    DevOps Training
    DevOps Online Training

    ReplyDelete
  6. Awesome article. It is so detailed and well formatted that i enjoyed reading it as well as get some new information too.
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  7. It won't work if you send a NULL

    ReplyDelete
  8. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea.
    here by i also want to share this.
    Java training in Chennai

    Java training in Bangalore

    Java online training

    Java training in Pune

    ReplyDelete
  9. Thank you for taking the time and sharing this information with us. It was indeed very helpful and insightful while being straight forward and to the point.
    Best Devops Training in pune
    Devops Training in Bangalore
    Power bi training in Chennai

    ReplyDelete
  10. Thanks For Sharing The information The Information Shared Is Very Valuable Please Keep Updating us The Information shared Is Very Valuable Python Online Course Data Science Online Course Aws Online Course

    ReplyDelete
  11. Attend The Python Training in Bangalore From ExcelR. Practical Python Training in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Bangalore.

    ReplyDelete
  12. I like viewing web sites which comprehend the price of delivering the excellent useful resource Python classes in pune free of charge. I truly adored reading your posting. Thank you!

    ReplyDelete
  13. Nice Blog, Thanks For Sharing Your information Please keep updating us. The Information you Shared Is Very valuable, keep it up!! Machine Learning Training in Bangalore

    ReplyDelete
  14. Attend The Data Analytics Courses in Bangalore From ExcelR. Practical Data Analytics Courses in Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses in Bangalore.
    ExcelR Data Analytics Courses in Bangalore

    ReplyDelete
  15. After reading your blog, I was quite interested to learn more about this topic. Thanks. Machine Learning Training In Bangalore

    ReplyDelete
  16. Hiii...Thanks for sharing Great info...Nice post...Keep move on...
    Angular JS Training in Hyderabad

    ReplyDelete
  17. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    angularjs online training

    ReplyDelete
  18. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

    ReplyDelete
  19. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it.

    data science course

    ReplyDelete
  20. Really it was an awesome article about JAVA, very interesting to read.You have provided an nice article,Thanks for sharing.
    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  21. I have to search sites with relevant information on given topic and provide them to teacher our opinion and the article.

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  22. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance
    Simple linear regression
    data science interview questions

    ReplyDelete
  23. This is my first time visit here. From the tons of comments ExcelR Machine Learning Courses on your articles.I guess I am not only one having all the enjoyment right here!

    ReplyDelete
  24. This splendid article really deserves a courteous bow down. I must own up that this article is very helpful.
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

    ReplyDelete
  25. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

    Simple Linear Regression

    Correlation vs covariance

    KNN Algorithm

    Logistic Regression explained

    ReplyDelete
  26. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!

    data science interview questions

    ReplyDelete
  27. Attend The Business Analytics Courses From ExcelR. Practical Business Analytics Courses Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analytics Courses.
    Business Analytics Courses

    ReplyDelete
  28. I really thank you for the valuable info on this great subject and look forward to more great posts ExcelR Business Analytics Courses

    ReplyDelete
  29. Terrific post thoroughly enjoyed reading the blog and more over found to be the tremendous one. In fact, educating the participants with it's amazing content. Hope you share the similar content consecutively.
    Data Analytics Course in Raipur

    ReplyDelete
  30. Thanks for posting the best information and the blog is very helpful.python course in Bangalore

    ReplyDelete
  31. Thanks for posting the best information and the blog is very helpful.data science interview questions and answers

    ReplyDelete
  32. Thanks for posting the best information and the blog is very helpful.Data science course in Faridabad

    ReplyDelete