我想以某种方式在打字稿中实现以下目标:
export type CoordinateSelector = <T>(d: Coordinate) => d[T];
export interface LinkVerticalLineProps {
x: CoordinateSelector<'x'>;
y: CoordinateSelector<'y'>;
}
我不想像这样创建x
和y
坐标选择器:
export interface LinkVerticalLineProps {
x: (d: {x: number}) => d.x;
y: (d: {y: number}) => d.y;
}
这种事情有可能吗?
答案 0 :(得分:2)
如果您的问题仅涉及打字,答案将是:
export type CoordinateSelector<T extends keyof Coordinate> = (d: Coordinate) => typeof d[T];
export interface LinkVerticalLineProps {
x: CoordinateSelector<'x'>;
y: CoordinateSelector<'y'>;
}
interface
仅是一种类型-无法执行。您仍然需要提供运行时将存在的实际代码。例如:
const getX: CoordinateSelector<'x'> = coordinate => coordinate.x;
答案 1 :(得分:0)
您正在寻找这种建筑吗?
export class A<T> {
public g: new () => T;
public o: T;
constructor(g: { new(): T }) {
this.g = g;
this.o = new this.g();
}
}