aws / aws/aws-appsync-community

optional chaining operator ?. doesn't work with a switch

Open
#411 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
HTML
Stars
507
Forks
37
PR merge metrics
No merged PRs in 30d

Description

The following snippets behave differently:

## Case 1: Optional Chaining (doesn't work)
```typescript
switch(a?.foo) {
// different string literal cases with a default
// ALWAYS lands on the `default` case
}
```

## Case 2: Simple variable, optional chaining evaluated into a local variable
```typescript
const val = a?.foo;
switch(val) {
// different string literal cases with a default
// matches the expected case
}
```

The difference in behavior is surprising.

## Troubleshooting
- I found this when some code failed to execute as expected post deployment
- The JS-Resolvers worked as expected in local Jest tests running in `node`
- Logging in AppSync confirmed that `a?.foo` was not `undefined` and evaluated to a string that matched a `case`
- Adding an `if` statement above the `switch` showed the `a?.foo` expression matched the same literal value used for the `case`
- Changing to the local var worked
- Changing the `switch/case` to `if/else` worked
- No other `switch/case` in the app were using `?.` so I hadn't seen this before

## Workarounds
- avoid `?.` within the switch's expression, storing the evaluated expression in a local variable
- use `if/else` instead since the `?.` works fine in these statements

Contributor guide

Open the contributing guide

Research direction

Reproduce the two switch forms from the issue in an AWS AppSync JavaScript resolver, comparing the deployed behavior with the local Jest tests running in Node. Start with the resolver snippets and AppSync runtime behavior, and verify the optional-chained value against the matching case literal. Done means establishing a minimal reproduction and documenting a runtime fix or confirmed workaround.

Written by the indexing model from the issue text.

Assessment

Tech stack
aws, graphql, node.js, typescript
Domain
api, backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Needs clarification
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.