Types in object destructuring

前端 未结 4 1262
你的背包
你的背包 2020-11-27 13:40

This

const { foo: IFoo[] } = bar;

and this

const { foo: Array } = bar;

will reasonably cause

相关标签:
4条回答
  • 2020-11-27 14:07

    A follow-up to my own question.

    Types don't need to be specified for object properties because they are inferred from destructured object.

    Considering that bar was typed properly, foo type will be inferred:

    const bar = { foo: [fooValue], ... }; // bar type is { foo: IFoo[], ... }
    ...
    const { foo } = bar; // foo type is IFoo[]
    

    Even if bar wasn't correctly typed (any or unknown), its type can be asserted:

    const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]
    
    0 讨论(0)
  • 2020-11-27 14:23

    It turns out it's possible to specify the type after : for the whole destructuring pattern:

    const {foo}: {foo: IFoo[]} = bar;
    

    Which in reality is not any better than plain old

    const foo: IFoo[] = bar.foo;
    
    0 讨论(0)
  • 2020-11-27 14:25

    I'm clearly a bit late to the party, but:

    interface User {
      name: string;
      age: number;
    }
    
    const obj: any = { name: 'Johnny', age: 25 };
    const { name, age }: User = obj;
    

    The types of properties name and age should be correctly inferred to string and number respectively.

    0 讨论(0)
  • 2020-11-27 14:31

    NextJS Typescript example

    I had scenarios like so:

    const { _id } = req.query;
    if (_id.contains('whatever')) { // typescript complained
     ...
    }
    

    in which the "req.query" was typed like string | string[] from NextJS... so doing this worked:

    const { _id } = req.query as { _id: string };
    if (_id.contains('whatever')) { // typescript is fine
     ...
    }
    

    The irony of this is Typescript was correct but I don't want to do the actual programming work to handle strings and string arrays.

    0 讨论(0)
提交回复
热议问题