Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: as const string array field causing readonly error

Tags:

typescript

The following example has a ts error at test

type Test = {
    obj: object;
    arr: string[];
};

export const test: Test = {
    obj: {},
    arr: ['foo'],
} as const;

saying:

Type '{ readonly obj: {}; readonly arr: readonly ["foo"]; }' is not assignable to type 'Test'. Types of property 'arr' are incompatible. The type 'readonly ["foo"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.

I want to use as const (causing the error) with test cuz test should never be changed. At the same time I will have other mutable variables of type Test, so I can't have any of the fields be readonly. How do I make the error go away with my goal in mind?

Confusingly, obj causes no error. Arrays are technically objects.

like image 283
sdfsdf Avatar asked Oct 15 '25 15:10

sdfsdf


1 Answers

This seems to work:

type Test = {
    obj: object;
    arr: string[];
};

export const test: Test = {
    obj: {},
    arr: ['foo'] as string[]
} as const;
like image 172
smac89 Avatar answered Oct 19 '25 19:10

smac89