代码之家  ›  专栏  ›  技术社区  ›  msanford

inline-partial<t>仍然抱怨缺少字段?

  •  0
  • msanford  · 技术社区  · 7 年前

    使用typescript~3.1.6,我已经声明了此接口:

    export interface Shop {
      readonly displayName: string;
      name: string;
      city: string;
    }
    

    哪里 displayName 由后端设置,用户界面无法更改。

    我创建了以下服务来创建一个新的商店,其余的需要 city name 作为属性:

    createShop = (shop: Partial<Shop>) =>
      this._http.post(`/shop/new`, shop, this._options)
        .pipe(
          catchError(this.handleError)
        );
    

    我将数据(从角度7反应形式)传递给大家:

    createShop = () =>
      this._shopService.createShop({
        name: this.form.get('name').value,
        city: this.form.get('city').value
      }).subscribe(/* handlers */);
    

    我已经声明create方法的商店是 Partial<Shop> 因为我不想分开 <CreateShop> 界面,我认为这正是 Partial<T> 我们赞成。

    然而,我在编译时仍然会得到这个错误:

    src/app/addShop.component.ts(39,40): error TS2345: Argument of type '{ name: string; city: string; }' is not assignable to parameter of type 'Shop'.
      Property 'displayName' is missing in type '{ name: string; city: string; }'.
    

    如果我声明

    export interface CreateShop extends Partial<Shop> {}
    

    用这个代替 部分<商店> 它编译。

    为什么我不能用在线 Partial 宣言?

    尤其是这似乎正好与 Partial<T> only works with inline values

    1 回复  |  直到 7 年前
        1
  •  2
  •   Nidhal Ben Tahar    7 年前

    您可以通过将对象文本强制转换为 Shop

    createShop = () =>
      this._shopService.createShop({
        name: this.form.get('name').value,
        city: this.form.get('city').value
      } as Shop).subscribe(/* handlers */);
    
    
    推荐文章