skip to Main Content

I’m getting this error when trying to convert my input data into the structure i need, but i don’t see any typings errors.

 The element is implicitly of type "any" because an expression of type "string" cannot be used to index the type "DocsInfo".
  No index signature found in type "DocsInfo" with parameter of type "string".ts(7053)

my code

type DocsInfo = {
    title: string;
    active?: number[];
    progress?: number[];
    closed?: number[];
};

const dict: Record<string, string> = {
        active: 'Is Active',
        progress: 'In Progress',
        closed: 'Is Closed',
};

const mappedArray = (arr: number[]) =>
    arr.map((item) => ({ key: String(item), content: item }));


const transformedArray = (data: DocsInfo) => {
        return Object.keys(data).filter((key) => key !== 'title')
            .map(key => ({
                label: dict[key], 
                options: mappedArray(data[key]) // The element is implicitly of type "any" because an expression of type "string" cannot be used to index the type "DocsInfo".
  No index signature found in type "DocsInfo" with parameter of type "string".ts(7053),
            })
    )};

my input data is

const data: DocsInfo = {
    active: [1, 2, 3],
    closed: [11, 22],
    progress: [111],
    title: '',
};

2

Answers


  1. You can replace the label and options with this:

    label: dict[key as keyof DocsInfo],
    options: mappedArray(data[key as keyof DocsInfo])

    This shoul work

    Login or Signup to reply.
  2. This error arises because Typescript expects to access the object keys, not just using any string but the actual key strings.

    In your case, we can call dict["active"], dict["progress"] or dict["closed"].
    Typescript is throwing error because allowing type of key to be string would allow the user to do something like dict["random_string"]

    You could type the key while mapping like the following:

    const transformedArray = (data: DocsInfo) => {
            return Object.keys(data)
                     .filter((key) => key !== 'title')
                     .map((key: keyof typeof dict) => ({
                        label: dict[key], 
                        options: mappedArray(data[key]) 
                      }))
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search