简体   繁体   English

如何在函数参数中键入提示特定对象

[英]How to type hint specific objects in function argument

Suppose I have some function:假设我有一些功能:

const someFunc = (input) => {// do something}

Where I know the input is an object that will have the property thing , ie.我知道输入是一个具有属性thing的对象,即。 in the function I might check what input.thing is.在函数中,我可能会检查input.thing是什么。 How do I type hint the function when I declare it?声明函数时如何键入提示函数? I tried something like:我试过类似的东西:

const someFunc = (input: { thing: string }) => {// do something}

But that doesn't seem to work.但这似乎不起作用。

That works just fine.这工作得很好。 You are declaring the first argument is an object with thing as a required string.您正在声明第一个参数是一个对象,其中thing是必需的字符串。

https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBFMBbApgMQK4RHAvHACgEsIAHDGALjgG84YALEgc2tgCcW4BfASjwB8tYHFFxw0MABsUAOilhmxMhVmMWvANzBuwRKkzYCNdRFZwA5AxRSFFvsCA https://www.typescriptlang.org/play?#code/FAYw9gdgzgLgBFMBbApgMQK4RHAvHACgEsIAHDGALjgG84YALEgc2tgCcW4BfASjwB8tYHFFxw0MABsUAOilhmxMhVmMWvANzBuwRKkzYCNdRFZwA5AxRSFFvsCA

const someFunc = (input: { thing: string }) => {
}

It can be helpful to work it out with a type instead of inline, just because inline types look kind of like destructuring.使用类型而不是内联来解决它会很有帮助,因为内联类型看起来有点像解构。

type Input = {
    thing: string
}
const someFunc = (input: Input) => {}

You might want to allow other keys, but require thing in which case you can add [key: string]: any to your object.您可能希望允许其他键,但需要在这种thing下您可以添加[key: string]: any到您的对象。

暂无
暂无

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

相关问题 有没有办法在Javascript中将传递的参数类型提示给IDE(在我的案例中是Webstorm)? - Is there a way to hint the passed argument type to IDE (in my case Webstorm) in Javascript? 如何将 typescript 类型添加到数组到 function 参数中? - How to add typescript type to an array into function argument? 如何有条件地在 typescript 中设置 function 参数类型? - How to conditionally set a function argument type in typescript? 如何通过前一个参数的值推断函数参数的类型? - How to deduce the type of function argument by value of previous argument? 如何根据Typescript中的字符串参数定义函数的参数类型? - How to define a function's argument type dependent on string argument in Typescript? 这个 function 参数的类型是什么? - What is the type of this function argument? JS在对象内部传递带有绑定的参数以访问对象范围内特定变量的最佳实践 - JS Best practice for passing argument with bind to function inside object to access specific variable inside objects scope 如何正确键入将对象数组转换为对象对象的函数 - How to properly type function that convert array of objects into object of objects Javascript - 如何检查特定“索引”处的函数中的参数是否丢失? - Javascript - How to check if argument in function at specific 'index' is missing? 如何为 JavaScript 中的特定参数只调用一次 function? - How to call a function only once for a specific argument in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM