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

Interface: Pass two array of specific length as prop

I have an interface like this

interface FooProps {
    cat: string[],
    kitten: number[],
}

Is there any way to tell TypeScript that kitten and cat must be the same length? Note, the length varies, depending on where the interface FooProps is used. But, whenever I use FooPros, the length of cat and kitten must be the same.

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 :

interface FooProps {
  cat: string[];
  kitten: number[];
}

// If cat and kitten are of fixed same length then
// the easiest way would be to define them as supple

interface FooPropsAsTupple {
  cat: [string, string];
  kitten: [number, number];
}

const catsTupples: FooPropsAsTupple = {
  cat: ["", ""],
  kitten: [1, 2],
};

// however if they are dynamic, then you need to validate
// using a class (There are other ways too but this is easy)

class Felines implements FooProps {
  constructor(props: FooProps) {
    if (props.cat.length !== props.kitten.length) {
      throw new Error(`Cat and kitten must have the same length`);
    }
    const { cat, kitten } = props;
    this.cat = cat;
    this.kitten = kitten;
  }
  public cat!: string[];
  public kitten!: number[];
}

// Error: Cat and kitten must have the same length
new Felines({ cat: ["", "", ""], kitten: [1, 2] });

You may even combine both approach in order to get type completion but also actual safety by throwing error.

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