Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unreachable code is not detected for methods that return never #56049

Closed
patrickkunka opened this issue Oct 10, 2023 · 8 comments
Closed

Unreachable code is not detected for methods that return never #56049

patrickkunka opened this issue Oct 10, 2023 · 8 comments
Labels
Question An issue which isn't directly actionable in code

Comments

@patrickkunka
Copy link

patrickkunka commented Oct 10, 2023

🔎 Search Terms

  • type narrowing
  • return type never
  • error
  • throw
  • method
  • chaining
  • error 7027

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for any entries relating to return type never

⏯ Playground Link

https://tsplay.dev/wQqAZw

💻 Code

const throwError = (message: string): never => {
  throw new Error(message);
}

type Thrower = typeof throwError;

const errorContext = {
  throwError
};

type ErrorContext = typeof errorContext;

const test1 = (thrower: Thrower) => {
  throw new Error('foo');

  // following code results in 7027 "unreachable code detected" as expected

  console.log('bar');
};

const test2 = (thrower: Thrower) => {
  thrower('foo');

  // following code results in 7027 "unreachable code detected" as expected

  console.log('bar');
};

const test3 = (errorContext: ErrorContext) => {
  errorContext.throwError('foo');

  // following code does NOT result in 7027, although the code is unreachable at runtime

  console.log('bar');
};

🙁 Actual behavior

If a function that returns never is a method, it does not result in error 7027 "unreachable code detected" or any
expected type-narrowing for subsequent code when called.

🙂 Expected behavior

Any code after a call to a function that always returns never should result in error 7027 "unreachable code detected" and any expected type-narrowing regardless of whether that function is method or a standalone function.

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

This is working as intended. See #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.

Your errorContext has an implicit type.

@patrickkunka
Copy link
Author

Interesting thank you - I've just added an explicit type for the errorContext and I can see it resolves the issue. Let me revert to my actual project as don't believe I'm using an implicit type there, so the issue may be more nuanced.

@patrickkunka
Copy link
Author

patrickkunka commented Oct 10, 2023

Having looked at my actual code, it seems the same issue and resolution still applies.

The intended pattern looks like this:

errorManager
    .error(
        ConcurrencyMessageId._005_CONCURRENCY_REFRESH_REJECTION,
        serviceError.status,
        serviceErrorResponse['odata.error']?.code.toString() ?? '',
        serviceErrorResponse['odata.error']?.message.value ?? '',
    )
    .throw({
        args: [
            ['httpStatus', Number],
            ['errorCode', String],
            ['errorMessage', String],
        ],
    });

// TS is not aware that core here is unreachable

Where the return type of .error() is inferred based on the arguments provided to it using generic parameters.

Based on your advice, unfortunately it seems the only way to get TS to correctly infer the control flow, is to break up the function chain and explicitly apply that inferred type to the error context:

const errorContext: IErrorContext<[httpStatus: number, errorCode: string, errorMessage: string]> = errorManager
    .error(
        ConcurrencyMessageId._005_CONCURRENCY_REFRESH_REJECTION,
        serviceError.status,
        serviceErrorResponse['odata.error']?.code.toString() ?? '',
        serviceErrorResponse['odata.error']?.message.value ?? '',
    );

errorContext.throw({
    args: [
        ['httpStatus', Number],
        ['errorCode', String],
        ['errorMessage', String],
    ],
});

// TS is aware that any core here is unreachable

This is obviously quite verbose and a no go for DX given it makes the inference provided redundant by forcing the author to explicitly type it.

So still curious is this is really the intention / expected behaviour here? If so, could it be improved?

@MartinJohns
Copy link
Contributor

So still curious is this is really the intention / expected behaviour here?

It is, and it's done for performance reasons. It's unlikely for change.

@Beraliv
Copy link

Beraliv commented Oct 10, 2023

@MartinJohns I'm curious what is the expected behaviour for explicit type when there are multiple chainable options (I have depth of 2 in my example below). Currently it doesn't have 7027 "unreachable code detected"

I believe it meets all the criterias that you've mentioned above (correct me if I'm wrong)

TypeScript Playground - https://tsplay.dev/Ndy4dm

@MartinJohns
Copy link
Contributor

Having explicit types is just one requirement. See the list above.

the call specifies a single identifier or a dotted sequence of identifiers for the function name, and

Your prepare() call is interfering with this requirement.

@Beraliv
Copy link

Beraliv commented Oct 10, 2023

@MartinJohns so errorContext.prepare.throw('bar'); would work but as I have a function, it's not allowed. Got you, thanks

@RyanCavanaugh RyanCavanaugh added the Question An issue which isn't directly actionable in code label Oct 10, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Question" 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
Labels
Question An issue which isn't directly actionable in code
Projects
None yet
Development

No branches or pull requests

5 participants