Home > Net >  How to add TypeScript Interface to shorthand variable?
How to add TypeScript Interface to shorthand variable?

Time:01-26

How to set TypeScript interface to variable looking like this:

const { body, statusCode } = await got.post('smth', requestOpts)

How can I set the interface to ex. body. I would like to assign there an interface with potential requests from the server. An interface that I'm willing to implement looks like that:

    interface ResponseBody {
        data: [{ username: string }]
    }

I tried different things to attach this interface to the upper variable body but I'm getting build errors. The only workaround that I have here is to do not use shorthand variable but that's not my goal - I wonder if there are solutions for such issue.

TypeScript Playground

CodePudding user response:

You'd need to annotate the whole object, like this:

const { body, statusCode }: { body: ResponseBody, statusCode: number } =
    await got.post<ResponseBody>('users', requestOpts)

While it would be nice if you could annotate the individual destructured variables inside the object, this is not currently possible. The syntax const { body: ResponseBody } = ... can't work because JavaScript interprets this as assigning to a new variable name (so there'd be a variable named ResponseBody holding the value that was in the body property). Perhaps something like const { body::ResponseBody, statusCode::number } would work instead, as requested in microsoft/TypeScript#29526. But for now this is not possible, and you have to annotate the whole object.


That's the answer to the question as asked.

Do note that for your particular example, though, the got.post() method has a call signature that's generic in the type you expect the body property to be. So you can write

const { body, statusCode } = await got.post<ResponseBody>('users', requestOpts);

to get a strongly typed body variable with a minimum of extra keystrokes.

Playground link to code

  •  Tags:  
  • Related