类型与打字稿中的可选参数不匹配

type does not match with optional parameter in typescript

我对打字稿中的类型有一个疑问。我正在做一些需要包含一些包的项目,我发现一些道具是包中的可选类型。但是,在我的代码中,它是必需的,所以我有错误

Type 'TypePackageVariable' is not assignable to type 'Record<string, string>'.
  Index signature is missing in type 'TypePackageVariable'

示例代码

interface TypePackageVariable {
  paraA: string;
  paraB?: string;
}
const packageVaribale:TypePackageVariable = {paraA: 'paraA', paraB:'paraB'}
const localVariable: Record<string, string> = packageVaribale
console.log(localVariable)

我该如何解决?

问题是 Typescript 无法将 TypePackageVariable 视为 Record<string, string> 的子集。

有一篇非常好的文章解释了 Typescript 中的索引签名 - https://basarat.gitbook.io/typescript/type-system/index-signatures

我可以想到两种方法来明确说明并解决您的问题 -

  1. 将值转换为 Record 的显式子集
const localVariable: Record<string, string> = packageVariable as Record<'paraA' | 'paraB', string>;
  1. 在声明类型时扩展 Record
interface TypePackageVariable extends Record<string, string> {
  paraA: string;
  paraB?: string;
}