2

I am quite new to Typescript and I am having little trouble with a interface implemenation.

The interface I have (from d3.js types) :

export interface AxisScale<Domain> {
    (x: Domain): number | undefined;
    domain(): Domain[];
    range(): number[];
    copy(): this;
    bandwidth?(): number;
    // TODO: Reconsider the below, note that the compiler does not differentiate the overloads w.r.t. optionality
    // ticks?(count?: number): Domain[];
    // ticks?(count?: AxisTimeInterval): Date[];
    // tickFormat?(count?: number, specifier?: string): ((d: number) => string);
    // tickFormat?(count?: number | AxisTimeInterval, specifier?: string): ((d: Date) => string);
}

This is how I am trying to implement the interface:

export class Axis implements AxisScale<number> {

    domain(): (number)[] {
        return [5];
    }

    range(): number[] {
        return [5, 10]
    }

    copy(): this {
        return this;
    }

    bandwidth?(): number {
        return d3.scaleBand().align();
    }

    side: 't' | 'b' | 'l' | 'r';
    color: string = "#000000";
    padding: number;
    margin: Margin;
}

When I save my file and I get this error:

Type 'Axis' provides no match for the signature '(x: number): number'.

How do I implement the anonymous object((x: Domain): number | undefined;) in my class?

0

2 Answers 2

2

(x: Domain): number | undefined; describes a function signature. A class can't implement an interface that contains an index signature, only a function can:

export interface AxisScale<Domain> {
  (x: Domain): number | undefined;
  domain(): Domain[];
  range(): number[];
  copy(): this;
  bandwidth?(): number;
}

const CreateAxis = function (): AxisScale<number> {
  function Axis(this: typeof Axis, x: number): number {

    return 0
  }
  Axis.domain = function (): number[] {
    return [5];
  }

  Axis.range = function (): number[] {
    return [5, 10]
  }

  Axis.copy = function <T>(this: T): T {
    return this;
  }
  //   side: 't' | 'b' | 'l' | 'r';
  Axis.color= "#000000";
  Axis.padding = 0

  return Axis;
};

let axis = CreateAxis();
axis(10)
axis.domain()

Playground Link

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

Comments

1

AxisScale interface defines a function type with additional properties so:

const AxisFunction: AxisScale<number> = (x: Domain) => {
  // ... content of function
}

AxisFunction.domain = (): number[] => {
  return [5];
}

AxisFunction.range = (): number[] => {
  return [5, 10]
}

AxisFunction.copy = (): AxisScale<number> => {
  return this;
}

AxisFunction.bandwidth = (): number => {
  return d3.scaleBand().align();
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.