I have one question about the type in typescript. I am working on some project that required to included some package that I found the some props is optional type from package. however, in my code, it is as required so I have the error
Type 'TypePackageVariable' is not assignable to type 'Record<string, string>'.
Index signature is missing in type 'TypePackageVariable'
example code
interface TypePackageVariable {
paraA: string;
paraB?: string;
}
const packageVaribale:TypePackageVariable = {paraA: 'paraA', paraB:'paraB'}
const localVariable: Record<string, string> = packageVaribale
console.log(localVariable)
how can I fix it?
The issue is that Typescript is unable to see TypePackageVariable
as a subset of Record<string, string>
.
There is a really nice article explaining index signatures in Typescript - https://basarat.gitbook.io/typescript/type-system/index-signatures
There are two ways I can think of to make it explicit and fix your issue -
const localVariable: Record<string, string> = packageVariable as Record<'paraA' | 'paraB', string>;
interface TypePackageVariable extends Record<string, string> {
paraA: string;
paraB?: string;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.