Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "as const satisfies" with array of objects to get "as const" benefits with type checking

Tags:

typescript

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:

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.

like image 968
sloppy Avatar asked Dec 14 '25 04:12

sloppy


1 Answers

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[];
like image 136
vighnesh153 Avatar answered Dec 16 '25 23:12

vighnesh153



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!