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

How to create a typescript type to allow read-only tuples from a const

I have the following interface

interface Test {
    data: string[]
}

const DATA_LIST = {
    USER: ["some string"],
    OTHER: ["some other string", "random value", "etc"]
} as const;

const test : Test = {
    data: DATA_LIST.OTHER
}

In the above code I cannot assign DATA_LIST.OTHER to data which is my use case where I have a couple of tuples that I want to assign to data.

I cannot assign it because it only accepts string[] while I am trying to assign a readonly tuple

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

Is there a better way to do this?

https://www.typescriptlang.org/play?ssl=12&ssc=2&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgCoQM5mQbwFDKHIAmcYcAXMllKAOYDaAungL554ID2IWyAIgEFUggPoAZAJIBlVMgC8uAkQCq0gKIAlKgwBEGLgFsUNerqYAaZYQDyqABJad+oyi5gAFtGphaIOroWyLpQcCDERsgAbnAANgCuEIHBEGAI5mzIcBjI3LxgANwceXyQfFTofIr4RCRklALCYlKyAHR2jppsQA

>Solution :

The underlying problem is simply this:

The type 'readonly ["some other string", "random value", "etc"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.

… which means that you can’t assign a string[] to a readonly string[].

If you want to reassign test.data at some other point in time, then you could simply do data: [...DATA_LIST.OTHER], which will get rid of the readonly aspect and which allows you to assign to a simple string[] property.

If you do not want test.data to be reassigned you could change the type of the property to either readonly string[] or string[] | readonly string[].

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