Skip to content

Wrong "possibly 'undefined'" assertion #29344

Closed
@xobotyi

Description

@xobotyi

TypeScript Version:
3.2.2

Search Terms:
Cannot invoke an object which is possibly 'undefined'.
Object is possibly 'undefined'.

Code:

type ElementRef = (element: HTMLElement | null) => void;

type ThumbProps = React.HTMLProps<HTMLDivElement> & {
  elementRef?: ElementRef;
}

type ComponentProps = React.HTMLProps<HTMLDivElement> & {
  thumbYProps?: ThumbProps;
}

class Component extends React.Component<ComponentProps>{
  public thumbYElementRef  = (ref: HTMLElement | null) => {
    this.thumbYEl = ref;
    typeof this.props.thumbYProps!.elementRef === 'function' && this.props.thumbYProps!.elementRef(ref);
  };
}

Expected behavior:
Compillation without errror.
Due to previous check typeof this.props.thumbYProps!.elementRef === 'function' it can't be undefined.

Actual behavior:
Cannot invoke an object which is possibly 'undefined'.
Problem solves if add non-null assertion, but it is unnecessary here!

// this one will compile fine
  public thumbYElementRef  = (ref: HTMLElement | null) => {
    this.thumbYEl = ref;
    typeof this.props.thumbYProps!.elementRef === 'function' && this.props.thumbYProps!.elementRef!(ref);
  };

Playground Link:

Related Issues:

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScript

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions