Typescript:索引签名内的扩展语法与类型不兼容

问题描述 投票:0回答:2

给出这个例子:

type Foo = {
  [key: string]: {
    bar: "bar",
    baz: string[],
    qux: string,
  };
}

const obj = {
  bar: "bar",
  baz: ["baz"],
};

const a: Foo = {
  key: { // error TS2322: Type '{ bar: string; baz: string[]; qux: string; }' is not assignable to type '{ bar: "bar"; baz: string[]; qux: string; }'.
    qux: "qux",
    ...obj,
  },
};

console.log(a);

如何在保持强类型的同时避免此错误?我尝试将

as const
添加到
partial
,但随后遇到了此错误:

The type 'readonly ["baz"]' is 'readonly' and cannot be assigned to the mutable type 'string[]'.
typescript
2个回答
0
投票

仅在关键栏上使用

as const
,而不是整个对象。

type Foo = {
  [key: string]: {
    bar: "bar",
    baz: string[],
    qux: string,
  };
}

const obj = {
  bar: "bar" as const, // <-- HERE
  baz: ["baz"],
} // as const; <-- NOT HERE

const a: Foo = {
  key: { 
    qux: "qux",
    ...obj,
  },
};

console.log(a);

TS游乐场


0
投票

如果使用 typescript > 5,则可以使用

satisfies
。如果你要写在哪里

const a = 'hi' as const satisfies string

a
的类型是
hi
。但是写

const a = 4 as const satisfies string

会给你一个错误

type 'number' does not satisfy the expected type 'string'

所以对于你的例子来说可能是

const obj = {
  bar: "bar",
  baz: ["baz"],
} satisfies Partial<Foo[string]>;
© www.soinside.com 2019 - 2024. All rights reserved.