简体   繁体   中英

Is there a way for typescript to infer arguments object or have a type defined for arguments object?

I have a type like the following:

type success = (data: any, value: string, settings: any) => void

OR an interface like the following

// interface success { (data: any, value: string, settings: any): void }

I have an object like this { onSuccess: (<need to have 'success' type here for arguments>) => { callbackFunction(<call using the same arguments passed to OnSuccess function>) } }

  • Is there a way to have arguments object passed to onSuccess function be type inferred to success type? If so how do I define an interface or a type signature similar to success type above that can be used to be type inferred?

Try using the built-in Parameters

type success = (data: any, value: string, settings: any) => void

const fn = (...args: Parameters<success>) => {}

if the order of the object arguments are always the same you might be able todo something with Object.values and the spread operator

Object.values : https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/values

> const fn = (a, b, c) => ({a,b,c})
undefined
> fn({a: 5, b: 3, c:2})
{ a: { a: 5, b: 3, c: 2 }, b: undefined, c: undefined }
> fn(...Object.values({a: 5, b: 3, c: 2}))
{ a: 5, b: 3, c: 2 }

where Object.values({a: 5, b: 3, c: 2}) is equal to [5, 3, 2]

Although I would not recommend this and would just add some code to map them directly to prevent bugs later on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM