简体   繁体   中英

TypeScript Interface Required property based on another property

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) {
  
}

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

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