[TypeScript]: Typing Object Entries

Hello all,

I am stuck with the following typing problem - I want to strongly type this, but cannot figure out how it should be done:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ path: () => void; scripts: () => void; preview?: (() => void) | undefined; bashrc?: (() => void) | undefined; }'.
  No index signature with a parameter of type 'string' was found on type '{ path: () => void; scripts: () => void; preview?: (() => void) | undefined; bashrc?: (() => void) | undefined; }'.ts(7053)

Relevant Code

Types

type Bashrc =
  | { enabled: true; path: string }
  | { enabled: false; path?: string };

type Preview =
  | {
      open: true;
      url: string;
    }
  | { open: false; url?: string };

export interface Config {
  path: string;
  scripts: {
    "develop-course": string;
    "run-course": string;
    test?: string;
  };
  preview?: Preview;
  bashrc?: Bashrc;
}

Type Usage

const conf: { [T in keyof Config]: () => void } = {
  path: (val) => {},
  scripts: (val) => {},
  preview: (val) => {},
  bashrc: (val) => {},
};

export async function handleConfig(config: Config) {
  const entries = Object.entries(config);
  entries.forEach(([key, value]) => {
    conf[key](value);
  });
}

I realise I could explicitly add each and every type, but I know there is a better way to do this. So, I am trying to approach this from the perspective that handleConfig could be generic:

function handleConfig<T>(config: T) {}

Any help is appreciated :slightly_smiling_face:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.