Home > Net >  Typescript create class property whose value will be used as another type's property name
Typescript create class property whose value will be used as another type's property name

Time:03-29

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?

CodePudding user response:

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.

CodePudding user response:

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

  • Related