How to exclude a key from an interface in TypeScript

后端 未结 4 505
既然无缘
既然无缘 2021-02-05 04:38

In TypeScript, you can combine two interface types like this

interface Foo {
    var1: string
}

interface Bar {
    var2: string
}

type Combined = Foo & Ba         


        
相关标签:
4条回答
  • 2021-02-05 04:45

    There is utility-types library that has Subtract mapped type:

    import { Subtract } from 'utility-types';
    
    type Props = { name: string; age: number; visible: boolean };
    type DefaultProps = { age: number };
    
    type RequiredProps = Subtract<Props, DefaultProps>;
    // Expect: { name: string; visible: boolean; }
    
    0 讨论(0)
  • 2021-02-05 04:46

    In TypeScript 2.8 you can now do the following:

    interface Foo {
        attribute1: string;
        optional2?: string;
        excludePlease: string;
    }
    
    // Typescript 3.5+ defines Omit for you.
    // In earlier Typescript versions define Omit:
    // type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
    
    // Use Omit to exclude one or more fields (use "excludePlease"|"field2"|"field3" etc to exclude multiple)
    type Bar = Omit<Foo, "excludePlease">
    const b: Bar = {
        attribute1: ''
    };
    

    So in relation to your question the following might be what you want:

    export default function valueHOC<P> (
      Comp: React.ComponentClass<P> | React.StatelessComponent<P>
    ): React.ComponentClass<Omit<P, "value">> {
      return class WrappedComponent extends React.Component<Omit<P, "value">, State> {
        render () {
          return (
            <Comp
              {...this.props}
              value={this.state.value}
            />
          )
        }
    }
    
    0 讨论(0)
  • 2021-02-05 05:00
    interface MyDialogProps extends Omit<DialogProps, 'onClose'> {
      id: string;
      onClose: (reason: string) => void;
    }
    
    export const MyDialog: React.FC<MyDialogProps> = ({ id, onClose, ...props) => (
      <Dialog onClose={() => onClose("whatever")} {...props} />
    );
    
    0 讨论(0)
  • 2021-02-05 05:06

    You can't remove properties from already existing interfaces. Even trying to extend existing interface with the interface having value property set as optional will return an error.

    To avoid this issue, modify the typings of the target component so value property is optional.

    e.g.

    // ...
    class MyComponent extends React.Component<{value?: string}, State> {
    // ...
    }
    

    and then component produced when using High Order Function

    const valuedComponent = valueHOC(MyComponent);
    

    won't ask for value prop.

    0 讨论(0)
提交回复
热议问题