I have run into a TypeScript problem while attempting to create a utility function for registering a Vue plugin. Below is a simplified version of the code:
import { type Component, type Plugin } from 'vue'
export type ComponentWithInstall<T> = T & Plugin
export type WithInstallPlugin = { _prefix?: string }
export function withInstall<C extends Component, T extends WithInstallPlugin>(
component: C | C[],
target?: T
): string {
const componentWithInstall = (target ?? component) as ComponentWithInstall<T>
const components = Array.isArray(component) ? component : [component]
const { name } = components[0]
if (name) {
return name
}
return ""
}
When testing in the TypeScript Playground, the error message highlights the name
property in red.
const { name } = components[0]
shows an error: Property 'name' does not exist on type 'Component'.(2339)
If I remove
const componentWithInstall = (target ?? component) as ComponentWithInstall<T>
, everything works without any issues. This issue seems related to type narrowing and may be related to the type assertion. I would appreciate some assistance in understanding this problem.