0

I want to somehow achieve something like this in typescript:

export type CoordinateSelector = <T>(d: Coordinate) => d[T];

export interface LinkVerticalLineProps {
  x: CoordinateSelector<'x'>;
  y: CoordinateSelector<'y'>;
}

I don't want to create x and y coordinate selectors like this:

export interface LinkVerticalLineProps {
  x: (d: {x: number}) => d.x;
  y: (d: {y: number}) => d.y;
}

Is this type of thing possible?

1
  • 1
    What's Coordinate? Are you just asking for type CoordinateSelector<K extends keyof Coordinate> = (d: Coordinate) => Coordinate[K] maybe? I'm not sure what you mean since the code you wrote at the bottom does not compile. Commented Dec 11, 2018 at 19:47

2 Answers 2

2

If your question is about the typings only, the answer would be:

export type CoordinateSelector<T extends keyof Coordinate> = (d: Coordinate) => typeof d[T];

export interface LinkVerticalLineProps {
  x: CoordinateSelector<'x'>;
  y: CoordinateSelector<'y'>;
}

An interface is a type only — it cannot be executed. You still need to supply actual code that will exist in runtime. For example:

const getX: CoordinateSelector<'x'> = coordinate => coordinate.x;
Sign up to request clarification or add additional context in comments.

2 Comments

yes, this is types only. is there a name for this pattern? i’m struggling to find any docs
I don't think it has a name — but you can find more when you look for "keyof" and "lookup types". See typescriptlang.org/docs/handbook/release-notes/…
0

Are you looking for this construction?

export class A<T> {
    public g: new () => T;
    public o: T;

    constructor(g: { new(): T }) {
        this.g = g;
        this.o = new this.g();
    }
}

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.