【问题标题】:Restrict typescript interface to not have few properties from parent限制打字稿接口不具有来自父级的少量属性
【发布时间】:2021-05-07 14:19:46
【问题描述】:

我有两个打字稿界面如下:

interface A {
    elem1: string;
    elem2: string;
    elem3: string;
    elem4: string;
}

interface B extends A {
   elem5: string;
}

现在我希望当我定义一个B 类型的变量时,它不应该有来自接口A 的elem1elem2。 打字稿中有没有办法做到这一点?

【问题讨论】:

    标签: typescript inheritance interface


    【解决方案1】:

    Omit Keys 是你的朋友。它是一种通过省略提供的键来构造类型的实用程序类型。

    这是一个例子

    TS Playground Link

    interface A {
        elem1: string;
        elem2: string;
        elem3: string;
        elem4: string;
    }
    
    interface B extends Omit<A, "elem1" | "elem2"> {
       elem5: string;
    }
    
    // Error
    const b: B = {
        elem2: 'sdsd',
        elem3: 'wewe',
        elem4: 'wewe',
        elem5: 'wewe',
        
    }
    
    // OK
    const b1: B = {
        elem3: 'wewe',
        elem4: 'wewe',
        elem5: 'wewe',
    }    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-17
      • 2017-06-29
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 2021-09-23
      相关资源
      最近更新 更多