首页 > 解决方案 > 基于输入对象字段的函数的通用返回类型

问题描述

我想要一个基于 Input 对象的返回类型。我们在函数中实现了一个猫鼬风格的字段选择器,我想实现依赖于输入对象字段的返回类型。

以下代码示例应说明问题:

interface IFields {
  _id: number;
  name: string;
  value1: string;
  value2: string;
  value3: string;
  value4: string;
  value5: string;
  value6: string;
}

export interface IFieldsSelector<T> {
    fields: {
        [key in keyof T]?: boolean;
    };
}

interface IResult extends IFields{ }

const select = (payload: IFieldsSelector<IFields>): IResult => {
  return {} as IResult;
};

const result = select({
  fields: {
    _id: true,
    value1: true,
  }
});

result.value1; // ok
result._id; // ok

result.name // error

TS游乐场

标签: typescript

解决方案


我们可以将输入键定义为泛型类型参数(打字稿会推断它),然后从以下位置选择它们IFields

export interface IFieldsSelector<T extends PropertyKey> {
  fields: {
    [key in T]?: boolean;
  };
}

interface IResult extends IFields { }

const select = <T extends keyof IFields>(payload: IFieldsSelector<T>): Pick<IFields, T> => ({} as IResult);

const result = select({
  fields: {
    _id: true,
    value1: true,
  }
});

result.value1; // ok
result._id; // ok

result.name // now error

操场


推荐阅读