简体   繁体   中英

type does not match with optional parameter in typescript

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 -

  1. Cast the value as an explicit subset of Record<string, string>
const localVariable: Record<string, string> = packageVariable as Record<'paraA' | 'paraB', string>;
  1. Extend Record<string, string> while declaring the type
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM