Priyanka Pyati
Priyanka Pyati

Reputation: 87

Partial classes in typescript

files.ts

export class ServiceUrls {
 static baseUrl: string = 'http://localhost:52949/V1/';
    static baseImageUrl: string = 'http://localhost:52949/';
}

filess1.ts

extends interface  ServiceUrls{
 static baseUrl: string = 'http://localhost:52949/V1/';
    static baseImageUrl: string = 'http://localhost:52949/';
}

How to implement partial class in typescript.How should i give reference of same class to make it work like partial class.If i give same class name in files1.ts its giving error declaration or statement expected.

Upvotes: 6

Views: 7310

Answers (2)

Jack Wang
Jack Wang

Reputation: 482

According to github issues, they have their concerns of not implementing the partial keyword. Therefore, you will need to write it yourself.

This task is no more than mixing prototypes. However, if you want a reliable one, you need to be very careful with method and property conflicts, also with type inference support.

I've written one and published on npm package partial_classes. You can use it by npm i partial_classes. And here is a simple method shows how to do this.

function combineClasses<T>(...constructors: T[]) {
    class CombinedClass {
        constructor(...args: any[]) {
            constructors.forEach(constructor => {
                const instance = new constructor(...args); // copy instance property
                Object.assign(this, instance);
            });
        }
    }

    constructors.forEach(constructor => { // copy prototype property
        let proto = constructor.prototype;
        while (proto !== Object.prototype) { // iterate until proto chain ends
            Object.getOwnPropertyNames(proto).forEach(name => {
                const descriptor = Object.getOwnPropertyDescriptor(proto, name);
                if (!descriptor) return;
                Object.defineProperty(CombinedClass.prototype, name, descriptor);
            });
            proto = Object.getPrototypeOf(proto);
        }
    });
    return CombinedClass
}

then use as

import combineClasses from 'partial_classes'
class ServiceUrlsFoo { }
class ServiceUrlsBar { }
const ServiceUrls = combineClasses(ServiceUrlsFoo, ServiceUrlsBar)
const instance = new ServiceUrls()

Upvotes: 0

Mustafah
Mustafah

Reputation: 4487

I created and I'm using @partial decorator acts as a simplified syntax that may help divide functionality of a single class into multiple class files ... https://github.com/mustafah/partials

Upvotes: 2

Related Questions