Home > Blockchain >  Typescript omit argument from generic function type
Typescript omit argument from generic function type

Time:01-05

How to omit prop type from generic function?

declare function func1<T extends {...}>(params: {age: number, something: T, ...more}): string

declare function func2<FunctionType extends (...args: any) => any>(cb: FunctionType): FunctionType
const newFunction = func2(func1)  // returns same type as func1
newFunction<{...}>({something: {...}, age: ...}) // is valid, but age should not be valid

in func2 how to remove property age from first argument of FunctionType?

I tried:

declare function func2<FunctionType extends (...args: any) => any>(cb: FunctionType): 
(params: Omit<Parameters<FunctionType>[0], 'age'>) => ReturnType<FunctionType>

const newFunction = func2(func1)  // This returns the new function type without age, but also without generics
newFunction<{...}>({...})   // the generic is no longer valid, bit is should be

This way I can remove the property age, but the return type is no longer generic. How I can keep it generic and omit the age from the first argument?

CodePudding user response:

Not sure what you need that generic for since you don't seem to use it, but this should do:

declare function func2<P extends {}, R>(f: (params: P) => R)
   : (params: Omit<P, 'age'>) => R
  • Related