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) { } https://stackoverflow.com/questions/67048097/typescript-interface-required-property-based-on-another-property April 12, 2021 at 01:23AM
没有评论:
发表评论