Search code examples
javascriptreactjstypescriptjavascript-objectsobject-destructuring

destruct object with interface


I have this code:

const {items} = this.props;

but, I need to set the interface into the items constant

and I do not want to do this:

const items: ItemsInterface = this.props.items

Possible?


Solution

  • As Oblosys stated in his comment, the preferred approach should be to destructure a well typed source object and rely on type inference.

    Type annotation syntax interacts awkwardly with and inconveniently with the destructuring syntax.

    Still, if you really wish to ascribe a type in the destructuring expression, there are a few ways.

    1. The simplest is to apply a type assertion to the right hand side of the expression

      const {items} = <{items: ItemsInterface}>this.props;
      

      Or equivalently

      const {items} = this.props as {items: ItemsInterface};
      

      Of course this is verbose, but it is clear, correct, and obvious.

    2. Perhaps closer to your instinct, you can specify the type of the destructuring expression with a type annotation as you would any other.

      const {items}: {items: ItemsInterface} = this.props;
      

      I personally find this awkward and a bit hard to read. The type annotation being ascribed to the unnamed expression {items}.

    3. If you are incidentally specifying a default value in the destructuring expression, you can actually specify the type inline.

      const {items = <ItemsInterface>{}} = this.props;
      

    Or equivalently

        const {items = {} as ItemsInterface} = this.props;
    

    In any case, there is no way to avoid repeating the name items unless you are initializing with a default value.

    I prefer the first option, since it is cleaner to alter the type of an existing value, here this.props, with an assertion applied to that value than to add a type annotation to the receiving declaration, here items, since the latter offers no intuition to the reader that the type is being manually adjusted.