Skip to content

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

Closed
@flavianh

Description

@flavianh

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

Activity

changed the title [-]NonNullable not properly casting generic types when excluding nullish values[/-] [+]NonNullable not properly casting generic type when excluding nullish values[/+] on Feb 26, 2022
jcalz

jcalz commented on Feb 26, 2022

@jcalz
Contributor

Feels like #33912

fatcerberus

fatcerberus commented on Feb 26, 2022

@fatcerberus

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

RyanCavanaugh commented on Feb 28, 2022

@RyanCavanaugh
Member

See e.g. #22348

typescript-bot

typescript-bot commented on Mar 3, 2022

@typescript-bot
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdFix AvailableA PR has been opened for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Participants

      @jcalz@fatcerberus@flavianh@RyanCavanaugh@typescript-bot

      Issue actions

        NonNullable not properly casting generic type when excluding nullish values Β· Issue #48048 Β· microsoft/TypeScript