0

I have few functions defined like below and I tried defining the type as : {[key: string]: any } and : {[key: string]: Function } but due to the eslint rules, no-explicit-any and ban-types I couldn't use those type definitions.

The reason for the below structure is that I have a dynamic code that calls the below function based on the value ( ex: someDefinition(someVar), where someVar is based on a value passed)

 const someDefinitions: {[key: string]: any } = {
    A: (v: string): string => 'Returning A',
    B: (v: string): string => 'Returning B with ' + v,
    C: (v: string): string => 'Returning C',
 };

Is there any way to define the types satisfying the rules?

Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134

1 Answers1

1

You could create an interface:

interface Foo {
  A(v: string): string;
  B(v: string): string;
  C(v: string): string;
};

Or type:

type Foo = {
  A(v: string): string;
  B(v: string): string;
  C(v: string): string;
};

And use it as the type of someDefinitions:

const someDefinitions: Foo = {
  A: (v: string): string => 'Returning A',
  B: (v: string): string => 'Returning B with ' + v,
  C: (v: string): string => 'Returning C',
};

You can even short-hand the object now that it's typed:

const someDefinitions: Foo = {
  A: (_v) => 'Returning A',
  B: (v) => 'Returning B with ' + v,
  C: (_v) => 'Returning C',
};

Usage:

console.log(someDefinitions.A(''));
console.log(someDefinitions.B('Foo'));
console.log(someDefinitions.C(''));
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Thanks. Sorry, I missed to mention the function names in the someDefinition is dynamic and they are based off a keys defined in json. – Selvakumar Arumugam Mar 13 '23 at 16:36
  • @SelvakumarArumugam What does the JSON typically look like? Have you tried [`zod`](https://www.totaltypescript.com/tutorials/zod)? – Mr. Polywhirl Mar 13 '23 at 17:31