Búsqueda de sitios web

javascript - Getters dinámicos y configuraciones para clases en TypeScript


Tengo un problema para recuperar datos con un getter dinámico en mi clase.

Aquí está el error que obtengo:

El elemento tiene implícitamente un tipo 'any' porque una expresión de tipo 'string' no se puede usar para indexar el tipo 'UserProps'. No se encontró ninguna firma de índice con un parámetro de tipo 'string' en el tipo 'UserProps'.ts(7053)

Aquí está el código

interface UserProps {
  name?: string;
  age?: number;
}

export class User {
  constructor(private data: UserProps) {}

  get(propName: string): number | string {
    return this.data[propName];
  }

  set(update: UserProps): void {
    Object.assign(this.data, update);
  }
}

Respuesta #1

La solución más limpia que pude encontrar es la siguiente:

interface UserProps {
    name?: string;
    age?: number;
}

export class User {
    constructor(private data: UserProps) {}

    // Add generic magic here
    get<K extends keyof UserProps>(propName: K): UserProps[K] {
        return this.data[propName];
    }

    set(update: UserProps): void {
        Object.assign(this.data, update);
    }
}

Alternativamente, también puedes agregar un índice de clave arbitrario, así como actualizar el tipo para tu declaración get.

interface UserProps {
    name?: string;
    age?: number;
    // this next line is important
    [key: string]: string | number | undefined;
}

export class User {
    constructor(private data: UserProps) {}

    // number|string changed to number|string|undefined
    get(propName: string): number | string | undefined {
        return this.data[propName];
    }

    set(update: UserProps): void {
        Object.assign(this.data, update);
    }
}

Artículos relacionados