Skip to content

Cannot assert about union type of assertionsΒ #62513

Description

@nnnnoel

πŸ”Ž Search Terms

union type of type assertion

πŸ•— Version & Regression Information

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABAQwM6oKYCcqoIwAUAHgFyKpRYxgDmiAPomCALYBG2Di4AJhsNQw8AlGTSYcqREUQBvAL4BYAFChIsBCnTZcAJmJkKVWl179BIsdsnS5S5SogIKiFsgCeHAMqVqdALyIALLIUAAWAHRYyGA8cCwEwogAfIgADBEArIgA-IgA5EZ++RGoADYwEBiJiGRmAmBCANwqjs5Q5PEYAILWUGRQ7gAOGHDAWhK4eFyDI2MTOqi6iP4qiMGhkdGx8TWpGdl54ovTVpNLLQ6q4NDwSMg1smvrnSw9fQRunhg+xjTClxerg83l8tAiEDCyCw3SgBDSAJU9iAA

πŸ’» Code

function asserts1(x: string | number | undefined): asserts x {}
function asserts2(x: string | undefined): asserts x {}

const maybeString = Math.random() > 0.5 ? 'string'.slice() : undefined;

const someAssert: typeof asserts1 | typeof asserts2 =
  Math.random() > 0.5 ? asserts1 : asserts2;

function a() {
    someAssert(maybeString);
    maybeString.charAt(0);
}

πŸ™ Actual behavior

maybeString is string | undefined

πŸ™‚ Expected behavior

maybeString must have only string type

Additional information about the issue

Related: #59707

When i implementing lint rule for about assert functions, cannot be report error coz checker doesn't respect someAssert is assertion function.
oxc-project/tsgolint#222
https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/tests/rules/strict-boolean-expressions.test.ts#L3547

Activity

  1. MartinJohns commented on Sep 30, 2025

    @MartinJohns
    Contributor

    This is working as intended, as per #32695.

    A function call is analyzed as an assertion call or never-returning call when

    • the call occurs as a top-level expression statement, and
    • the call specifies a single identifier or a dotted sequence of identifiers for the function name, and
    • each identifier in the function name references an entity with an explicit type, and
    • the function name resolves to a function type with an asserts return type or an explicit never return type annotation.

    The last point is not fulfilled, as your variable resolves to a union type.

  2. typescript-bot commented on Oct 3, 2025

    @typescript-bot
    Contributor

    This issue has been marked as "Design Limitation" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions