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

object is possibly undefined even though check is done #34535

Closed
barroudjo opened this issue Oct 17, 2019 · 4 comments · Fixed by #44730
Closed

object is possibly undefined even though check is done #34535

barroudjo opened this issue Oct 17, 2019 · 4 comments · Fixed by #44730
Labels
Duplicate An existing issue was already created

Comments

@barroudjo
Copy link

TypeScript Version: 3.6.3

Search Terms: object is possibly undefined

Code

const foo = (bar: { baz?: { name: string } }) => {
    const isBarBazDefined = !!bar.baz;
    if(isBarBazDefined) console.log(bar.baz.name);
}

Expected behavior:
Typescript should not give an 'object is possibly undefined' error.

Actual behavior:
Typescript does give an 'object is possibly undefined' error.

Playground Link:
http://www.typescriptlang.org/play/?ssl=4&ssc=2&pln=1&pc=1#code/MYewdgzgLgBAZiEMC8MAUAjAhgJwFwwDeM2AXgPwHFhYC2ApgdDgJZgDmMAvtwJQoA+IgCgYYmKEiwWEAEK55pACL04begBMUMAIQ7sOAHRkA3KPEs4aGfJyKVasJv6SIIADb1D7kO0y5jLFJDGgZeMy4gA

Related Issues:
Couldn't find any.

I realise this is very simple case, but I haven't been able to find an existing issue or FAQ entry on the subject...

@jack-williams
Copy link
Collaborator

This is a duplicate of #12184 - narrowing results cannot be assigned to an identifier and reused.

@barroudjo
Copy link
Author

Thanks. Is there any recommended workaround, besides again doing the check ?

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Oct 17, 2019
@jack-williams
Copy link
Collaborator

@barroudjo The quick and easy way is a ! assertion:

const foo = (bar: { baz?: { name: string } }) => {
    const isBarBazDefined = !!bar.baz;
    if(isBarBazDefined) console.log(bar.baz!.name);
}

@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
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants