简体   繁体   English

嵌套Typescript接口中的Override属性

[英]Override property in nested typescript interface

I have a typescript interface like so: 我有一个打字稿界面,如下所示:

interface DataSku {
  fields: {
    sku: string;
  }
}

interface PostProduct {
  fields: {
    title: string;
    skus: DataSku[];
  }
}

Now I want to extend the Product interface so that each object in the skus array has an extra field. 现在,我想扩展Product接口,以便skus数组中的每个对象都有一个额外的字段。 So I tried this: 所以我尝试了这个:

interface Sku extends DataSku {
  stripe: Stripe.skus.ISku;
}

interface Product extends PostProduct {
  fields: PostProduct['fields'] & {
    skus: Sku[];
  }
}

In my code, I try a loop like so: 在我的代码中,我尝试这样的循环:

(product as Product).fields.skus.forEach(sku => console.log(sku.stripe));

This throws the following Typescript error: 这将引发以下Typescript错误:

Property 'stripe' does not exist on type 'DataSku'.

Have I extended the interface wrong? 接口扩展错误吗? The console does output my stripe object as expected, so it's just Typescript that isn't happy with the definition. 控制台确实按预期方式输出了我的stripe对象,因此只是Typescript对定义不满意。

A much more elegant (and working) approach for this would be to use generics . 为此,一种更为优雅(有效)的方法是使用泛型

Update PostProduct with a generic parameter that's used for the type of fields.skus : 更新PostProduct与同时使用的类型,泛型参数fields.skus

interface PostProduct<T extends DataSku = DataSku> {
  fields: {
    title: string;
    skus: T[];
  }
}

T extends DataSku means the type has to be a subtype of DataSku . T extends DataSku意味着类型必须是DataSku的子类型。 And we can even set a default value for T so PostProduct can also be used without having to specify the generic parameter. 而且,我们甚至可以为T设置默认值,因此也可以使用PostProduct而无需指定通用参数。

Now, for Product we just have to pass Sku as generic parameter: 现在,对于Product我们只需要传递Sku作为通用参数:

interface Product extends PostProduct<Sku> {}

Playground 操场


That said, if you want to it without generics and without modifying DataSku and PostProduct . 就是说,如果您希望不使用泛型且不修改DataSkuPostProduct You could do this: 您可以这样做:

interface Product extends PostProduct {
  fields: Omit<PostProduct['fields'], 'skus'> & {
    skus: Sku[];
  }
}

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM