【问题标题】:How to use "as const satisfies" with array of objects to get "as const" benefits with type checking如何使用对象数组的“as const 满足”以获得类型检查的“as const”好处
【发布时间】:2023-01-14 11:27:35
【问题描述】:

按预期工作:

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

不起作用:-(

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

例如 B 的错误:

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)

我阅读了 TypeScript 4.9 博客文章和来自 TypeScript 存储库的几个 GitHub 问题,但仍然不知道我做错了什么,或者是否有其他方法可以做我想做的事情。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    当您在数组上使用 as const 时,打字稿会将其视为 readonly。因此,您需要让您的satisfies 键入readonly

    export const exampleB = [{...}] as const satisfies readonly ExampleB[];
    

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 2021-07-24
      • 2020-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2012-01-14
      • 2021-11-02
      相关资源
      最近更新 更多