Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!