TypeScript泛型和函数参数

时间:2017-09-29 20:50:33

标签: typescript

我正致力于改进Rosie的defs,目前我们非常依赖any并且不会提供更多的安全保障。我现在有点陷入困境,可以使用一些建议。

我试图写一个表达以下内容的签名:

// this is invalid, but something like this is the goal
interface IFactory<T = any> {
  attr<K extends keyof T, D extends keyof T>(name: K, dependencies: D[], generatorFunction: (value1?: D[0], value2?: D[1], value3?: D[2]), value4?: D[3] => T[K]): IFactory<T>;
}

第二个参数中给出了一组键。它们的值作为参数以所提供的相同顺序传递给函数。我想避免不必要的类型转换,所以我们应该得到这个:

Factory.define<Person>('Person').attr('fullName', ['firstName', 'lastName', 'age'], (firstName, lastName, age) => {
   // it knows that firstName is a string, lastName is a string, age is a number

  if (age > 10) { 
    // this will error
    return age; 
  }

  return `${firstName} ${lastName};     
});

我能得到的最接近的是:

attr<K extends keyof T, D extends keyof T>(name: K, dependencies: D[], generatorFunction: (value1: T[D], value2: T[D], value3: T[D], value4: T[D]) => T[K]): IFactory<T>;

这将最多输入4个相关值,但调用它需要显式强制转换,并且它不会按正确的顺序设置类型:

// it knows that each of the three arguments are string | number
existingDefinition.attr('fullName', ['firstName', 'lastName', 'age'], (firstName: string, lastName: string, age: number) => `${firstName} ${lastName}`);

这使我有可能在没有破坏的情况下改变依赖关系的顺序,这是不好的。如果我提供的参数多于依赖值,它也不会给出错误。我想找到一种表达方式&#34; generatorFunction对于dependenciesT[DependencyName]类型的每个元素都有一个参数。&#34;

我希望这是有道理的。感谢任何人提供的任何帮助。

1 个答案:

答案 0 :(得分:2)

您需要为每个arity(签名)进行重载。例如,看看Reselect如何做事

/* one selector */
export function createSelector<S, R1, T>(
  selector: Selector<S, R1>,
  combiner: (res: R1) => T,
): OutputSelector<S, T, (res: R1) => T>;
export function createSelector<S, P, R1, T>(
  selector: ParametricSelector<S, P, R1>,
  combiner: (res: R1) => T,
): OutputParametricSelector<S, P, T, (res: R1) => T>;

/* two selectors */
export function createSelector<S, R1, R2, T>(
  selector1: Selector<S, R1>,
  selector2: Selector<S, R2>,
  combiner: (res1: R1, res2: R2) => T,
): OutputSelector<S, T, (res1: R1, res2: R2) => T>;
export function createSelector<S, P, R1, R2, T>(
  selector1: ParametricSelector<S, P, R1>,
  selector2: ParametricSelector<S, P, R2>,
  combiner: (res1: R1, res2: R2) => T,
): OutputParametricSelector<S, P, T, (res1: R1, res2: R2) => T>;

/* three selectors */
export function createSelector<S, R1, R2, R3, T>(
  selector1: Selector<S, R1>,
  selector2: Selector<S, R2>,
  selector3: Selector<S, R3>,
  combiner: (res1: R1, res2: R2, res3: R3) => T,
): OutputSelector<S, T, (res1: R1, res2: R2, res3: R3) => T>;
export function createSelector<S, P, R1, R2, R3, T>(
  selector1: ParametricSelector<S, P, R1>,
  selector2: ParametricSelector<S, P, R2>,
  selector3: ParametricSelector<S, P, R3>,
  combiner: (res1: R1, res2: R2, res3: R3) => T,
): OutputParametricSelector<S, P, T, (res1: R1, res2: R2, res3: R3) => T>;

// etc...

为每个参数设置重载,直到一个合理的数字(你期望多少?4?8?)和过去只使用非限制性泛型并让用户输入它。如果您有超过8个参数, 会伤害您键入。