简体   繁体   中英

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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