Skip to content

unknown non-null object type restriction bug #29618

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

Closed
rvion opened this issue Jan 28, 2019 · 1 comment
Closed

unknown non-null object type restriction bug #29618

rvion opened this issue Jan 28, 2019 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@rvion
Copy link

rvion commented Jan 28, 2019

TypeScript Version: 3.2.2

Search Terms:

unknown non-null object type restriction bug

Code

type Indexable = { [key: string]: unknown }
const data: Indexable = {}

function navigate(index: Indexable, seg: string | number): Indexable {
    if (seg in index) {
        const next = index[seg]
        // DONT WORKS
        if (next != null && typeof next === 'object') return next
        // Type 'object | null' is not assignable to type 'Indexable'.
        
        // WORKS
        // if (typeof next === 'object' && next != null) return next
    }
    throw new Error('--')
} 

Expected behavior:

those 2 lines should work the same

if (next != null && typeof next === 'object') return next
if (typeof next === 'object' && next != null) return next

Actual behavior:

they don't

Playground Link: https://www.typescriptlang.org/play/#src=type%20Indexable%20%3D%20%7B%20%5Bkey%3A%20string%5D%3A%20unknown%20%7D%0D%0Aconst%20data%3A%20Indexable%20%3D%20%7B%7D%0D%0A%0D%0Afunction%20navigate(index%3A%20Indexable%2C%20seg%3A%20string%20%7C%20number)%3A%20Indexable%20%7B%0D%0A%20%20%20%20if%20(seg%20in%20index)%20%7B%0D%0A%20%20%20%20%20%20%20%20const%20next%20%3D%20index%5Bseg%5D%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20DONT%20WORKS%0D%0A%20%20%20%20%20%20%20%20if%20(next%20!%3D%20null%20%26%26%20typeof%20next%20%3D%3D%3D%20'object')%20return%20next%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20Type%20'object%20%7C%20null'%20is%20not%20assignable%20to%20type%20'Indexable'.%0D%0A%20%20%20%20%20%20%20%20%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20WORKS%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20if%20(typeof%20next%20%3D%3D%3D%20'object'%20%26%26%20next%20!%3D%20null)%20return%20next%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20throw%20new%20Error('--')%0D%0A%7D%20%0D%0A

Related Issues:

@jack-williams
Copy link
Collaborator

Duplicate of #28131.

@weswigham weswigham added the Duplicate An existing issue was already created label Jan 28, 2019
@rvion rvion closed this as completed Jan 31, 2019
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

No branches or pull requests

3 participants