2

I'm faced with a situation where I need to create a class using a third-party interface (more specifically D3).

I want to create a class implementing the D3.Force interface, but my compiler just wont have it.

class CustomForce<NodeDatum extends D3.SimulationNodeDatum> implements D3.Force<NodeDatum, any> {
    // Some more code at some point
}

This throws the following error:

Class 'CustomForce<NodeDatum>' incorrectly implements interface 'Force<NodeDatum, any>'. 
Type 'CustomForce<NodeDatum>' provides no match for the signature '(alpha: number): void'

By inspecting the definition for D3.Force, I see the following:

export interface Force<NodeDatum extends SimulationNodeDatum, LinkDatum extends SimulationLinkDatum<NodeDatum> | undefined> {
    (alpha: number): void;
    initialize?(nodes: NodeDatum[]): void;
}

How do I implement an anonymous function taking in alpha as argument?!

1 Answer 1

2

I don't think that you'll be able to create a class that implements this sort of interface.
The interface defines a function which also has a property named initialize which is a function, and as far as I know you can't do that using a class.

You can however do this:

function CustomForce<NodeDatum extends D3.SimulationNodeDatum>(): D3.Force<NodeDatum, any> {
    const force = function(alpha: number): void {
        ...
    }

    force.initialize = function(nodes: NodeDatum[]) {
        ...
    }

    return force;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I suspected as such. Feels wrong to create a function in Typescript that has methods though...
Well, in js a function is an object, so technically there's no problem with that. I usually avoid that as well, but sometimes it's nice to have that option

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.