1

I want to define a function like this:

function someFunctionWithSomeConfigPassedIn(config: SomeConfig) {
  
}

SomeConfig interface looks like this:

interface SomeConfig {
  type: SomeEnumType;
  paramRequiredForType1?: any; // How do I make this required when type is Type1 but optional when type is other type?
  paramRequiredForType2?: any; // How do I make this required when type is Type2 but optional when type is other type?
  paramRequiredForType3?: any; // How do I make this required when type is Type3 but optional when type is other type?
}

It's based off an enum:

enum SomeEnumType {
  Type1 = 'Type1',
  Type2 = 'Type2',
  Type3 = 'Type3',
}

I want to make the additional params required based on SomeEnumType. How can I do that?

Should I just use union type instead?:

interface Type1Config {
  type: SomeEnumType.Type1;
  paramRequiredForType1: any;
}
interface Type2Config {
  type: SomeEnumType.Type2;
  paramRequiredForType2: any;
}
interface Type3Config {
  type: SomeEnumType.Type3;
  paramRequiredForType3: any;
}

function someFunctionWithSomeConfigPassedIn(config: Type1Config | Type2Config | Type3Config) {
  
}
1
  • It seems more convenient and clear to use union Commented Apr 11, 2021 at 18:51

1 Answer 1

2

This is a case for discriminated unions. They are explained in the Typescript handbook at https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.