Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading