Skip to content

type assertions affect the type narrowing of the subsequent codeΒ #58050

@a145789

Description

@a145789

πŸ”Ž Search Terms

Type Assertion type Narrowing

πŸ•— Version & Regression Information

  • This changed between versions 5.3.3 and 5.4.3

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.4.3#code/JYWwDg9gTgLgBAbzjAnmApnAwhcEB26+MANMmpgAoA2ArgObD5wC+cAZlLnAOQButdDwBQwgPRjyGbHAC82XJELEA2j3wBDEEIC6w9AA9IsKZhx5lMAOrAYACwCS+AM4wN1agB4AKgD45cN5wAGRwNAxM+kbQ8KjSNvZOru7U4YzM8kgA+mBQ6OzABgD8AFxwrlBM9Kyihsbw7LT4AMYwwARwAO62ji5uHp5YcIYwRAAmzgoWRKSBwwaj+BNwCb3JHmlMvgAUwnBwzYoEM2VDAD7YKjoke8gaUPToMKWBwgCUZRVViLeHfQdHSyrJL9agBbZuB5POBFIoA6bEN5wDSTcxKGbAvopHy+X4EVzw9HESbyACCUCgGhQADpgM5yZSUNtDgiYEi4SyifAyipOcdiHo8f8kJptKwAnzLM4VAAGHRwW7Adhwbai9BIhC3fZ5GC0KDMNW3FiibVPPXMABEFuExuEQA

πŸ’» Code

import { type Component, type Plugin } from 'vue'

// type C = Component['name']
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 ""
}

πŸ™ Actual behavior

image
the name property is underlined in red, indicating an error.

Property 'name' does not exist on type 'Component'.(2339)

The type C = Component['name'] is valid, as the name property exists within the Component type. When I remove const componentWithInstall = (target ?? component) as ComponentWithInstall<T>, everything returns to normal. Alternatively, if I uncomment type C = Component['name'], even though it's not used anywhere, the error disappears. Type assertions should not affect the type narrowing of subsequent code, but an error occurs. This code worked fine in version 5.3.3, but started to error in version 5.4.3.

πŸ™‚ Expected behavior

Ts don't report the error.

Additional information about the issue

No response

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFix AvailableA PR has been opened for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions