我如何定义对象类型包含泛型函数

时间:2018-10-26 10:08:46

标签: typescript

type People = {
    getLaptop: <L>(name: string) => L
}

const makePeople = ( getPeople: People) => {
    return getPeople.getLaptop
}

const us =  {
    getLaptop: (name: string) => ({type: 'Dell'})
}

makePeople(us) //err at us

版本:“打字稿”:“ ^ 3.1.2”

完整的错误消息如下:

[ts]
Argument of type '{ getLaptop: (name: string) => { type: string; }; }' is not assignable to parameter of type 'People'.
  Types of property 'getLaptop' are incompatible.
    Type '(name: string) => { type: string; }' is not assignable to type '<L>(name: string) => L'.
      Type '{ type: string; }' is not assignable to type 'L'.
const us: {
    getLaptop: (name: string) => {
        type: string;
    };
}

如何解决此问题。

1 个答案:

答案 0 :(得分:1)

您没有定义L是哪种类型。这是行不通的。但是,您可以这样做

type People<L> = {
    getLaptop: (name: string) => L
}

const makePeople = ( getPeople: People<{}>) => {
    return getPeople.getLaptop
}

const us =  {
    getLaptop: (name: string) => ({type: 'Dell'})
}