【问题标题】:Creating a function type that returns argument object with possible extra props创建一个函数类型,该函数类型返回带有可能额外道具的参数对象
【发布时间】:2021-01-17 18:31:24
【问题描述】:

我希望创建一个函数 flowLens,它采用具有特殊签名/类型的函数数组。

  • 函数只能有一个参数
  • 函数的 arg 应该是一个普通对象
  • 函数必须返回普通对象中所有相同的键/值类型
  • 该函数可以返回额外的/新的属性。

这是我的尝试:

type Plain = {[key: string]: any};
type SpecialFunction = <T extends Plain, R extends T & Plain>(props: T) => R;
    
function flowLens (...fns: SpecialFunction[]) {}

const invalidType = (props: { a: number }) => true;
const invalidNotArgs = (props: { a: number }) => ({ ducks: 1 });
const validOne = (props: { a: number }) => ({...props});
const validTwo = (props: { a: number }) => ({ ...props, b: 1 });

flowLens(invalidType)
flowLens(invalidNotArgs)
flowLens(validOne)
flowLens(validTwo)

Playground

可以这样做吗?如果有怎么办?

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    对于调用flowLens 时要验证的类型,您需要移动泛型以直接参数化SpecialFunction。以下应该有效:

    type SpecialFunction<T extends Record<string, any>> = (props: T) => T;
    
    function flowLens<T extends any[]>(...fns: {[K in keyof T]: SpecialFunction<T[K]>}) {}
    

    TypeScript 默认允许无关的属性,因此您不需要任何额外的处理来允许返回类型上的那些。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      相关资源
      最近更新 更多