简体   繁体   English

打字稿有没有办法推断参数对象或为参数对象定义类型?

[英]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>) } }我有一个这样的对象{ 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?有没有办法将传递给onSuccess函数的arguments对象类型推断为success类型? 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?如果是这样,我如何定义一个类似于上面的success类型的interfacetype签名,可用于类型推断?

Try using the built-in Parameters尝试使用内置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和扩展运算符做一些事情

Object.values : https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Object/values Object.valueshttps : //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]其中Object.values({a: 5, b: 3, c: 2})等于[5, 3, 2]

Although I would not recommend this and would just add some code to map them directly to prevent bugs later on.虽然我不推荐这样做,只是添加一些代码来直接映射它们以防止以后出现错误。

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

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