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

NonNullable not properly casting generic type when excluding nullish values #48048

Closed
flavianh opened this issue Feb 26, 2022 · 4 comments Β· Fixed by #49119
Closed

NonNullable not properly casting generic type when excluding nullish values #48048

flavianh opened this issue Feb 26, 2022 · 4 comments Β· Fixed by #49119
Labels
Duplicate An existing issue was already created Fix Available A PR has been opened for this issue

Comments

@flavianh
Copy link

Bug Report

πŸ”Ž Search Terms

Generic types nonnullable

πŸ•— Version & Regression Information

This bug appears to exist ever since NonNullable was introduced (tested from 3.3.3 to 4.5.4)

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function throwIfNullable<T>(
  value: T,
): NonNullable<T> {
  if (value !== undefinedΒ && value !== null) {
    return value;
  }

  throw Error('Nullable')
}

πŸ™ Actual behavior

The line return value raises a compilation error Type 'T' is not assignable to type 'NonNullable<T>'.

πŸ™‚ Expected behavior

No compilation error as the if clause properly guards against nullish values

@flavianh flavianh changed the title NonNullable not properly casting generic types when excluding nullish values NonNullable not properly casting generic type when excluding nullish values Feb 26, 2022
@jcalz
Copy link
Contributor

jcalz commented Feb 26, 2022

Feels like #33912

@fatcerberus
Copy link

fatcerberus commented Feb 26, 2022

An alternative construction that works would be:

function throwIfNullish<T>(value: T | null | undefined): asserts value is T
{
    if (value == null) throw Error("Nullish!");
}

declare let x: string | undefined;
throwIfNullish(x);  // x: string | undefined
x;  // x: string

@RyanCavanaugh
Copy link
Member

See e.g. #22348

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Feb 28, 2022
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' 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
Duplicate An existing issue was already created Fix Available A PR has been opened for this issue
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants