1

I got a class called MyClass. It has a bunch of properties. I want to create an interface that contains the options of that class. Many options have the same name and typing than MyClass, but not all.

Edit: Most options properties are optional.

The goal is to duplicate the least possible.

Right now, I'm using a dummy object to avoid code duplication. Is there a cleaner solution than this?

class MyClass {
    callback:(p0:number,p1:string,p2:string[]) => number[];
    myAttr:number;
    composed:string;

    constructor(options:MyClassOptions){
        if(options.callback !== undefined)
            this.callback = options.callback;
        if(options.myAttr !== undefined)
            this.myAttr = options.myAttr;
        if(options.composedP1 !== undefined && options.composedP2 !== undefined)
            this.composed = options.composedP1 + options.composedP2;
    }
}

var dummy = <MyClass>null; 
interface MyClassOptions {
    callback?:typeof dummy.callback;
    myAttr?:typeof dummy.myAttr;
    composedP1:string;
    composedP2:string;
}

1 Answer 1

1

Many options have the same name and typing than MyClass, but not all.

If this is the case, there's not a good option.

If you want to have exactly the same members, and your class doesn't have any private or protected properties/methods, you can write

interface MyClassOptions extends MyClass {
  extraProp: string;
}

One thing you could do is make a base class with just the options you want to share, make the interface from there with the "real" class you use being a derivative of the base class.

Sign up to request clarification or add additional context in comments.

1 Comment

One thing I forgot to mention explicitly is that all the properties in MyClassOptions are optional. This solution makes all the properties non-optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.