Home > Back-end >  How to type hint specific objects in function argument
How to type hint specific objects in function argument

Time:06-14

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.

CodePudding user response:

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.

  • Related