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 use "as const satisfies" with array of objects to get "as const" benefits with type checking

Work as expected:

interface ExampleA {
  id: number;
  name: `S${string}`;
}
export const exampleA = {
  id: 8455,
  name: 'Savory'
} as const satisfies ExampleA;

Doesn’t work 🙁

interface ExampleB {
  id: number;
  name: `S${string}`;
}
export const exampleB = [
  {
    id: 8455,
    name: 'Savory'
  }
] as const satisfies ExampleB[];

Error for exampleB:

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

Type 'readonly [{ readonly id: 8455; readonly name: "Savory"; }]' does not satisfy the expected type 'ExampleB[]'.
  The type 'readonly [{ readonly id: 8455; readonly name: "Savory"; }]' is 'readonly' and cannot be assigned to the mutable type 'ExampleB[]'.ts(1360)

I read TypeScript 4.9 blog post and couple of GitHub issue from TypeScript repo and still have no idea what I’m doing wrong or if there another way to do what I’m trying to do.

>Solution :

When you use as const on an array, typescript thinks of it as readonly. So, you need to make your satisfies type readonly.

export const exampleB = [{...}] as const satisfies readonly ExampleB[];
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