Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
Typescript create class property whose value will be used as another type's property name

I'm trying to create a class property that can be used to define another type:

class TypeOne {
    public static readonly key: string = 'key';
}

class TypeTwo { public [TypeOne.key]: TypeOne }

But it shows this error:

A computed property name in a class property declaration must have a simple literal type or a 'unique symbol'

It works fine with the constant value of an enum:

enum TypeThree {
    key = 'key'
}

class TypeFour { public [TypeThree.key]: TypeThree }

Is there any way to set a constant value on a class so that the compiler can accept it as an immutable key and understand the field name?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Get rid of the string annotation:

class TypeOne {
    public static readonly key = 'key';
}

class TypeTwo { public [TypeOne.key]: TypeOne }

TS needs a literal type for the property name, string is too broad.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can simply define TypeOne as:

class TypeOne {
    public static readonly key = 'key'; // Remove the string annotation
}

This makes the value of key constant which is the literal string 'key', since this is a unique value the compiler won't complain

Playground

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda