具有相同键的对象与打字稿中的另一个对象?

时间:2017-10-01 10:38:14

标签: typescript

我有一个方法produce,其签名如下:

interface ProduceConditions {
    [key: string]: Function|Promise<any>;
}

produce(conditions: ProduceConditions, input: any): Promise<object>|object;

问题是返回的(已解析的)对象与conditions对象具有相同的键。

编辑:我应该添加对函数源的引用,该函数位于https://github.com/selfrefactor/rambdax/blob/master/modules/produce.js

2 个答案:

答案 0 :(得分:7)

如果我理解您正确询问的内容,那么您的输入conditions将是ProduceConditions的实现,其中包含一些键和返回值(无论是否包含在承诺中) )将具有相同的键,但所有值都已解析。

在这种情况下,您正在寻找的签名将是:

produce<T extends ProduceConditions, U extends { [key in keyof T]: any }>(conditions: T, input: any): Promise<U> | U

这里我使用了两种泛型类型来表示输入和输出,要求输入类型T符合ProduceConditions的定义和输出类型{{1} }具有与U相同的键。

答案 1 :(得分:1)

如果输入应该是一个值为函数或promise的对象,并且输出是一个带有这些函数的对象,那么你可以使用mapped typesinference from mapped types来指定约束:

type ProduceConditionsMapper<T> = {
  [K in keyof T]: ((input: T[K]) => void) | Promise<T[K]>;
}

declare function produce<T>(conditions: ProduceConditionsMapper<T>, input: any): T;

行动中:

declare const func: (x: number) => void;    
declare const prom: Promise<string>;
const produceConditions = {
  cat: func,
  dog: prom
}

const ret = produce(produceConditions, 'hmm');
// inferred as {cat: number; dog: string;}

我不确定input与其他类型之间的关系是什么,但您可能会给它一个比any更具体的类型,以获得更好的结果。无论如何,希望有所帮助。

相关问题