Home > Mobile >  Ensure at least one property is provided to function
Ensure at least one property is provided to function

Time:05-16

I want to pass in either 1 of the 3 parameter string to the function. Is the following the best way? I am thinking if there is another more elegant way.

function (a: Option1 | Option2 | Option3) {
   // some code here
 }

interface Option1 {
  a: string
  b?: string
  c?: string
}

interface Option2 {
  a?: string
  b: string
  c?: string
}

interface Option3 {
  a?: string
  b?: string
  c: string
}

CodePudding user response:

Let's use a mapped type to solve this! We should, for each key, make that key required and all others optional.

To make everything else optional, we could omit the key and use the built-in Partial type.

And for just getting the key, we can use the built-in Pick type.

Finally, for the desired type, we intersect these:

type AtLeastOne<T> = {
    [K in keyof T]: Pick<T, K> & Partial<Omit<T, K>>;
}[keyof T];

Here's how you would use it:

type A = AtLeastOne<Option>; // create the possible types

function a(a: A) {} // and use it here

A few example calls:

a({}); // ! error

a({ a: "" });
a({ b: "" });
a({ c: "" });

a({ a: "", b: "" });
a({ a: "", b: "", c: "" });
a({ a: "", c: "" });

As you can see, you must provide at least one property to the function. Try it out yourself here.

CodePudding user response:

I believe what you want is this?:

function (type: OptionType) {
    // some code here
}

type OptionType = Option1 | Option2 | Option3;

interface Option1 {
    a: string
    b?: string
    c?: string
}

interface Option2 {
    a?: string
    b: string
    c?: string
}

interface Option3 {
    a?: string
    b?: string
    c: string
}
  • Related