指定参数必须具有keyof属性

时间:2018-12-12 19:28:43

标签: typescript

我有以下this和以下代码:

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]

1 个答案:

答案 0 :(得分:1)

您可以使用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;
    }
}