Skip to content

TypeScript doesn't correctly narrow types and detect unreachable code after calling redirect() #823

Open
@MinSeungHyun

Description

@MinSeungHyun

Description

When I use next/navigation's redirect, the type of userId is successfully narrowed to string because if userId is undefined it calls redirect() whose return type is never.
image

But when I use redirect from createSharedPathnamesNavigation, it's not working.
image
image

This is because of typescript's designed limitation. microsoft/TypeScript#36753

So I'm using redirect like this on my project. I re-declared redirect as a function not a const.

// navigation.ts
const navigation = createSharedPathnamesNavigation({
  locales,
  localePrefix,
});

export const { Link, usePathname, useRouter: useIntlRouter } = navigation;

export function redirect(...params: Parameters<typeof navigation.redirect>): never {
  return navigation.redirect(...params);
}

I think it should work by default when using next-intl's redirect as next's default redirect does.

Mandatory reproduction URL (CodeSandbox or GitHub repository)

https://codesandbox.io/p/devbox/next-intl-bug-template-app-forked-fp6873

Reproduction description

Steps to reproduce:

  1. Open reproduction
  2. Click on the file ./src/app/[locale]/intl/page.tsx
  3. See error: Type 'string | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'. on userId2
  4. But when you check default/page.tsx, intl2/page.tsx, it works fine,

Expected behaviour

The type error should not be occurred like other files.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workinghas-workaroundupstream-issueThis issue is caused by an upstream dependency (e.g. Next.js)

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions