简体   繁体   中英

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. in the function I might check what input.thing is. 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.

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.

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