简体   繁体   English

Typescript 省略通用 function 类型的参数

[英]Typescript omit argument from generic function type

How to omit prop type from generic function?如何从通用 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 ?func2中如何从FunctionType的第一个参数中删除属性age

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.这样我可以删除属性age ,但返回类型不再是通用的。 How I can keep it generic and omit the age from the first argument?我如何才能保持它的通用性并从第一个参数中省略age

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 typescript 中的泛型类型中省略? - How to Omit from generic type in typescript? 从TypeScript中的函数的参数类型推断通用类型参数 - Infer generic type argument from parameter type of function in TypeScript TypeScript:当其类型未定义时,省略通用 function 的尾随参数 - TypeScript: Omit trailing parameter of generic function when its type is undefined TypeScript:通用 function 类型参数是从错误参数推断的 - TypeScript: generic function type argument is inferred from a wrong parameter void 作为 TypeScript 中泛型函数的参数类型 - void as a type of an argument of a generic function in TypeScript 如何在 TypeScript 中使用通用和默认参数键入 function - How to type function with generic and default argument in TypeScript 打字稿通用函数更改参数类型 - Typescript generic function changing argument type Typescript function 省略某些键并从它的参数中添加其他键 - Typescript function to omit certain keys and add others from it's argument 具有特定泛型类型参数的泛型 function 的参数类型,在 typescript - Parameters type of a generic function with specific generic type argument, in typescript 为什么带有类型联合类型参数的泛型 TypeScript 函数不能推断出与返回类型相同的类型? - Why cannot a generic TypeScript function with an argument of type from a type union infer the same type as the return type?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM