-
Notifications
You must be signed in to change notification settings - Fork 13k
Closed
Labels
DuplicateAn existing issue was already createdAn existing issue was already created
Description
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
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
Related Issues:
Metadata
Metadata
Assignees
Labels
DuplicateAn existing issue was already createdAn existing issue was already created