首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >指定参数必须具有keyof属性

指定参数必须具有keyof属性
EN

Stack Overflow用户
提问于 2018-12-12 19:28:43
回答 1查看 18关注 0票数 1

我有以下代码的游乐场

代码语言:javascript
复制
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]的对象

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-12-12 19:39:22

您可以使用Pick只选择一个类型的属性:

代码语言:javascript
复制
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;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53750078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档