Can't access a field of an object in TypeScript by using a variable as a name of the index...

Discussão em 'Angular' iniciado por Konrad Viltersten, Dezembro 14, 2024.

  1. I can't understand why the first two printouts work, while the other two produce an error.

    const index1 = "name";
    this.sorting.field = "name";
    const index2 = this.sorting.field;

    console.log('element', this.data[0]["name"]);
    console.log('element', this.data[0][index1]);

    console.log('element', this.data[0][this.sorting.field]);
    console.log('element', this.data[0][index2]);


    The error says:


    TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'MyType'.
    No index signature with a parameter of type 'string' was found on type 'MyType'.
    ​

    How can I get a field by a variable name coming from a non-constant?

    I haven't found good answers addressing this specific issue in a way that I recognized. Most confusing is the fact that I am using a string to get the field in the object in both cases. The only difference is the const declaration.

    I've tried adding as const according to an example without any difference.

    The field value comes from this interface. It definitely is a string.

    export interface SortInfo {
    field: string;
    direction: number;
    }


    The object itself that I'm trying to get the field from is declare by this interface.

    export interface MyType {
    id: string;
    name: string;
    type: number;
    ...
    }

    Continue reading...

Compartilhe esta Página