简体   繁体   English

打字稿,是否可以在没有某种类型的情况下扩展接口?

[英]Typescript, is it possible to extend interface without some type?

import React from "react";

interface a_to_e {
  a?: string;
  b?: string;
  c?: string;
  d?: string;
  e?: string;
}

interface a_to_e_without_c extends a_to_e {
  // I'd like to implement a~e without c
}

function Child(props: a_to_e_without_c) {
  return (
    <>
      <div>child</div>
    </>
  );
}

function App() {
  return (
    <>
      <Child c="I'd like to throw compile error," />
    </>
  );
}

export default App;

Is is possible to extend interface in typescript except some special type?除了某些特殊类型外,是否可以在打字稿中扩展接口?

Of course it can be implemented by making custom exception,当然可以通过自定义异常来实现,

but I'd like to throw compile error ,但我想抛出编译错误

when some of my co-worker use Child component with property c.当我的一些同事使用带有属性 c 的子组件时。

Is it possible?是否可以?

You can use Omit utility of typescript您可以使用打字稿的省略实用程序

example:例子:

interface a {
  a: string,
  b: string,
  c: string
}

type without_c = Omit<a, "c">;

const variable_with_c: without_c = {
  a: "a",
  b: "b",
  c: "c" //compile error
}

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

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