typescript 如何对对象数组使用“as const satisfied”以获得“as const”对类型检查的好处

2fjabf4q  于 2023-01-18  发布在  TypeScript
关注(0)|答案(1)|浏览(163)

按预期工作:

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的博客文章和几个GitHub问题,仍然不知道我做错了什么,或者是否有其他方法来做我想做的事情。

eufgjt7s

eufgjt7s1#

当你在一个数组上使用as const时,typescript会认为它是readonly,所以你需要把你的satisfies类型设为readonly

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

相关问题