zeroin
zeroin

Reputation: 6025

Prevent part of Typescript code to be compiled

I have class A and class B, which extends class A. Class A has a method which accepts AProperties enum as first argument. Class B has the same method which accepts AProperties or BProperties enum as first argument.

enum AProperties {
    X,
    Y
}

enum BProperties {
    Z,
    W
}

class A {
    setProperty(property: AProperties, value: number) {

    }
}

class B extends A {
    setProperty(property: AProperties | BProperties, value: number) {

    }
}

setProperty method of class B is added only for typescript editor to know that this method can accept both AProperties and BProperties. When compiled to JavaScript, having setProperty in classB doesn't make any sense as it is 100% identical to classA method.

Is there a way to prevent this method to be compiled in JavaScript? I guess some comment before the method could do the job.

Upvotes: 0

Views: 74

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164357

I don't think that there's a way of asking the compiler to skip over code without commenting it out, but you can design things a bit differently and avoid the need to add implementation of the method in the child class:

enum AProperties {
    X,
    Y
}

enum BProperties {
    Z,
    W
}

class Base<T> {
    setProperty(property: T, value: number) {
        // ...
    }
}

class A extends Base<AProperties> {}

class B extends Base<AProperties | BProperties> {}

(code in playground)

This approach adds another class (Base) which actually has the implementation of setProperty and that happens just once, and in A and B you just declare the type of the property enum.

There's a discussion/suggestion to have default generic types which (when it's implemented) will make it easier, something like:

class A<T = AProperties> {
    setProperty(property: T, value: number) {}
}

class B extends Base<AProperties | BProperties> {}

But for now you'll need the Base class.


Edit

I thought of another solution, which you'll probably like better as it doesn't require the other class (Base):

interface Base<T> {
    setProperty(property: T, value: number);
}

class A implements Base<AProperties> {
    setProperty(property: AProperties, value: number) {
        // ...
    }
}

class B implements Base<AProperties | BProperties> {
    setProperty: (property: AProperties | BProperties, value: number) => void;
}

let a = new A();
a.setProperty(AProperties.X, 4);

let b = new B();
b.setProperty(AProperties.X, 4);
b.setProperty(BProperties.W, 4);

(code in playground)

Upvotes: 2

Related Questions