Skip to content

Ternary operator not narrowing down type inference #37291

@lonyele

Description

@lonyele

TypeScript Version: 3.7.2, nightly
This may be a newbie question since I couldn't find any similar questions on stack overflow or this repo... I think these examples will have a same behavior but it actually has different typescript checking result. Please guide me to a learning material if this question is asked because of purely not understanding javascript of typescript
스크린샷 2020-03-09 오후 8 57 43

Search Terms:
combinations of ternary operator, narrowing, type inference, type guard
Code

interface ExampleData {
    bitlyUrl?: string | undefined | null;
}

const exampleData: ExampleData = {
    bitlyUrl: 'https://bitly.com/asdfasasdf'
}

const help = (arg: string) => {
    console.log('function that has a argument with a string type')
}

exampleData && exampleData.bitlyUrl
    ? help(exampleData.bitlyUrl)
    : console.log('working as expected')

const condition1 = exampleData && exampleData.bitlyUrl;
condition1
    ? help(exampleData.bitlyUrl)
    : console.log('not working with variable')

const condition2 = exampleData?.bitlyUrl;
condition2
    ? help(exampleData.bitlyUrl)
    : console.log('not working with variable(optional chaining)')


const workaround = exampleData && exampleData.bitlyUrl;
workaround
    ? help(exampleData.bitlyUrl as string)
    : console.log('workaround that doesn't look ok....')

Expected behavior:
It should not make a typescript error

Actual behavior:
It emits typescript error

Playground Link: https://www.typescriptlang.org/play/?ts=3.9.0-dev.20200308#code/JYOwLgpgTgZghgYwgAgKIA84FsAOAbCAETjDmQG8AoZG5AI2DDwE8BVKPAfgC5kBnMFFABzZAB9kAVxAATCDFAQZ45CEl48AbkoBfSpQQB7EAOQRMuAsVK8M2fERJkAvBWq0GTNh14ByABZgYDh83AD0YZ4sAHRGWGFwfDLwfInJvrr6RiZgyP4QeDjIrgAUcFDCvAJCIMIAlMUAfG60yNl8hgTReIbCJb4w0ghgwMbIYP4keYnIZOXCklgQ4MgA7oz+s-yCIuPMOBC+dZmU5vZWTsgAZFdmFg7WcNFR3njuNJx5BTglZ5aOpGejBY7Dwx1avHanQg3V6-VWhigAGtdjNzAdhkojlljKZsjJGKMQABGYp3c4Asg3cn-R5Aryg7T4wnGYnvZCffKFX73C6Al6g8G0SG46Gwvq+ECGXII5G7dYTZAAN3KwDgdAI2IMuNyzJGxgATGS-g8nJx6SCOEzjAT9SADezOd8eRS6QKOEKaCKTGKehKpTLESjamsNsrVeqCCVDDg7XA8G1JqARHUtUA

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions