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.
>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.