我有一个关于打字稿类型的问题。我正在处理一些需要包含一些包的项目,我发现一些道具是包中的可选类型。但是,在我的代码中,它是必需的,所以我有错误
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)
我该如何解决?
答案 0 :(得分:2)
问题是 Typescript 无法将 TypePackageVariable
视为 Record<string, string>
的子集。
有一篇非常好的文章解释了 Typescript 中的索引签名 - https://basarat.gitbook.io/typescript/type-system/index-signatures
我能想到两种方法来明确说明并解决您的问题 -
const localVariable: Record<string, string> = packageVariable as Record<'paraA' | 'paraB', string>;
interface TypePackageVariable extends Record<string, string> {
paraA: string;
paraB?: string;
}