我有以下代码的游乐场:
export interface Coordinate {
x: number;
y: number;
}
export interface Line {
source: Coordinate;
target: Coordinate;
}
export type Selector<T, K extends keyof T> = (d: { [key: string]: K }) => typeof d[K];
export interface LinkVerticalLineProps {
x: Selector<Coordinate, 'x'>;
y: Selector<Coordinate, 'y'>;
}
class Foo implements LinkVerticalLineProps{
originX: number;
originY: number;
constructor({ x, y }: Coordinate) {
this.originX = x;
this.originY = y;
}
x(other: Coordinate) {
return other.x;
}
y(other: Coordinate) {
return other.x;
}
}但打字稿不高兴。
如何满足编译器的要求:x函数必须接受一个具有x属性并返回typeof d[K]的对象
发布于 2018-12-12 19:39:22
您可以使用Pick只选择一个类型的属性:
export interface Coordinate {
x: number;
y: number;
}
// Use Pick to pick out just one property
export type Selector<T, K extends keyof T> = (d: Pick<T,K>) => T[K]; // you can also use typeof d[K] but it's the same as T[K] but longer
//Does the same thing but less repeating the property names
export type LinkVerticalLineProps = {
[P in keyof Coordinate]: Selector<Coordinate,P>
}
class Foo implements LinkVerticalLineProps{
originX: number;
originY: number;
constructor({ x, y }: Coordinate) {
this.originX = x;
this.originY = y;
}
// We must repeat the Pick, ts will not infer class member argument types
x(other: Pick<Coordinate, 'x'>) {
return other.x;
}
y(other: Pick<Coordinate, 'y'>) {
return other.y;
}
}https://stackoverflow.com/questions/53750078
复制相似问题