Nickon
Nickon

Reputation: 10146

TypeScript and inheritance

I need a little help with TypeScript. How to do extension methods inheritance?

Lets say we have a class named MyClass with only one method Method1():

class MyClass {
   constructor () { }

   public Method1(): void {
   }
}

Now I want to make a sub class that adds a new method named Method2():

class MyClassExtension {
   public Method2(): void {
   }
}

When I have interfaces I can do this by declaring a new interface with the same name:

interface MyInterface {
   Method1(): void;
}

interface MyInterface {
   Method2(): void;
}

var x: MyInterface;
x.Method1(); // ok
x.Method2(); // ok

But I don't know how to do this for classes:/ Can any1 help me, please?

Thanks in advance!!!

Upvotes: 1

Views: 3110

Answers (2)

stopyoukid
stopyoukid

Reputation: 182

Based on your response to JohnnyHK's answer, can you do something like the following?

If your existing jquery.d.ts looks something like this:

interface JQuery {
    //...OTHER MEMBERS IN JQUERY
    addClass(classNames: string): JQuery;
    addClass(func: (index: any, currentClass: any) => JQuery);

    attr(attributeName: string): string;
    attr(attributeName: string, value: any): JQuery;
    //...OTHER MEMBERS IN JQUERY
}

interface JQueryStatic {
    //...OTHER MEMBERS IN JQUERY
    parent(selector?: string): JQuery;

    parents(selector?: string): JQuery;

    parentsUntil(selector?: string, filter?: string): JQuery;
    parentsUntil(element?: Element, filter?: string): JQuery;
    //...OTHER MEMBERS IN JQUERY
}


declare var jQuery: JQueryStatic;
declare var $: JQueryStatic;

Then all you would need to do in your code somewhere is define your extension methods, for example:

file1.ts

///<reference path='jquery.d.ts'/>
interface JQuery {
    myNewExtensionMethod() : string;
}
interface JQueryStatic {
    myNewExtensionMethod() : string;
}

jQuery.myNewExtensionMethod = () => {
    return "11";
}

$.myNewExtensionMethod = () => {
    return "11";
}

And then use them:

file2.ts

///<reference path='file1.ts'/>
var result = $.myNewExtensionMethod();

Upvotes: 2

JohnnyHK
JohnnyHK

Reputation: 311835

This is standard class inheritance, so you can do it like this:

class MyClassExtension extends MyClass {
   public Method2(): void {
   }
}

In your interface example, you're not declaring a new interface with the same name, you're splitting the MyInterface definition across two partial definitions. Interface definitions are open-ended but classes are not.

Upvotes: 10

Related Questions