Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typescript required param if other param = true

I have a typescript function with some params like that

myFunction(allData: Array<any>, selectedItems: Array<any>, onlyValues: boolean = false, values: Array<any>) {
    console.log(allData);
    console.log(selectedData);
    console.log(onlyValues);
    console.log(values);
}

If onlyValues is set to true, I want values to be required, else, I don’t need values

How to do this please

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could try with a guarded type:

type Values = {onlyValues: true, values: Array<any>} | {onlyValues: false}

Then you would pass (allData: Array<any>, selectedItems: Array<any>, v: Values) to the function.

You can try this TS Playground.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading