How to extend parameter types in TypeScript?

Viewed 26

How can I make prop2 in effect either optional or required depending on the specific instance of this class?

interface EffectParams {
  prop1: string;
  prop2?: string;
  prop3?: string;
}

interface WithProp2 extends EffectParams {
  prop2: string
}


class Class1 {
  effect: (params: EffectParams) => void;

  constructor(effect: (params: EffectParams) => void) {
    this.effect = effect;
  }
}

const a = new Class1(
  // ERROR HERE
  // Argument of type '({ prop1, prop2 }: WithProp2) => void' is not assignable to parameter of type '(params: EffectParams) => void'.
  ({ prop1, prop2 }: WithProp2) => {
    prop2.anotherProperty();
    // Can anotherProperty be used without optional chaining?
  }
);

const b = new Class1(
  ({ prop1, prop2 }: EffectParams) => {
    prop2?.anotherProperty();
    // more code
  }
);
1 Answers

I changed tha name a bit but here is how i would do it

interface UserEffectParams {
        name: string;
        age?: number
    }

interface CustomerEffectParams extends Required<UserEffectParams> {
    email: string;
}

class EffectManager<EffectParams extends UserEffectParams> {
    effect: (params: EffectParams) => void;

    constructor(effect: (params: EffectParams) => void) {
            this.effect = effect;
    }
} 

const a = new EffectManager<UserEffectParams>(({ name, age }) => {
    console.log({ name, age });
});
const b = new EffectManager<CustomerEffectParams>(({ name, age, email }) => {
    console.log({ name, age, email });
});
Related