[英]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.