1

i have interface for form validation

export interface SearchBarValidatorObj {
  [k: string]: KeyObjectValidator;
}

is there a way to add "static" type to it? To have this functionality

export interface SearchBarValidatorObj {
  required: string | boolean
  [k: string]: KeyObjectValidator;
}

this is KeyObjectValidator interface

interface KeyObjectValidator {
  value: string | number | RegExp;
  message?: string;
}

Cheers!

  • 1
    There is no specific type in TypeScript corresponding to what you're trying to do. There are various workarounds. See [the answer](https://stackoverflow.com/a/61434547/2887218) to the question this duplicates for more information. If I translate the code there to your example code, it produces [this](https://tsplay.dev/wXk9VW). Good luck! – jcalz Sep 28 '21 at 16:39

1 Answers1

0

Yes, you could use an intersection type:

export interface SearchBarValidatorObj {
  [k: string]: KeyObjectValidator;
}

interface KeyObjectValidator {
  value: string | number | RegExp;
  message?: string;
}

type WithStatic = SearchBarValidatorObj & { required: string | boolean };

let obj!: WithStatic;
// these are valid
obj.required = false;
obj.a = { value: 5 };

// these are invalid
obj.required = 4;
obj.required = { value: 5 };
vitoke
  • 660
  • 4
  • 11
  • Intersection types like this are one of the workarounds to the lack of "default" or "rest" index signatures. They are not easy to initialize since the compiler tries to check that the `required` property of any initial value will match the index signature, which it won't. In your answer you are avoiding initializing by writing `let obj!: WithStatic` (which essentially guarantees a runtime error... I suppose you could have written `let obj = {} as WithStatic` instead) but there's no type-safe way to do it. See [this answer](https://stackoverflow.com/a/61434547/2887218) for more explanation. – jcalz Sep 28 '21 at 16:44
  • Completely agree. Just wanted to give a possible solution for the stated problem. – vitoke Sep 28 '21 at 19:04