代码之家  ›  专栏  ›  技术社区  ›  Justin Grant

我可以指定通过TypeScript rest/spread赋值定义的新局部变量的类型吗?[副本]

  •  0
  • Justin Grant  · 技术社区  · 6 年前

    const { foo: IFoo[] } = bar;
    

    还有这个

    const { foo: Array<IFoo> } = bar;
    

    还有这个

    const { foo: TFoo } = bar;
    

    只会破坏结构 TFoo 财产。

    如何为非结构化对象属性指定类型?

    0 回复  |  直到 8 年前
        1
  •  227
  •   artem    8 年前

    结果是可以在 :

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

    事实上,这并不比普通的老年人好

    const foo: IFoo[] = bar.foo;
    
        2
  •  62
  •   Kristianmitk    6 年前

    我显然有点晚了,但是:

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

    name age string number 分别。

        3
  •  2
  •   Estus Flask    5 年前

    我自己问题的后续行动。

    bar 输入正确, foo 将推断类型:

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

    即使 酒吧 输入不正确( any unknown ),其类型可以断言为:

    const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]
    
        4
  •  2
  •   King Friday    4 年前

    我有过这样的情景:

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

    其中需求查询“打得像 string | string[] 从NextJS。。。所以这样做有效:

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