lit / lit/lit

[reactive-element] query decorator API doc examples don't type-check

Open
#3,612 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
21.8k
Forks
1.1k
Avg merge
18h 25m
Merged PRs (30d)
2

Description

### Which package(s) are affected?

Lit Core (lit / lit-html / lit-element / reactive-element)

### Description

The [query](https://lit.dev/docs/api/decorators/#query) decorator API docs show TS code that does not type-check (`Property has no initializer and is not definitely assigned in the constructor`):

```ts
@query('#first')
first: HTMLDivElement;
```

The most correct is to show it as nullable, since if you query before the first `update()` or if the template contains conditionals, it may return null:

```ts
@query('#first')
first: HTMLDivElement | null = null;
```

OTOH, most users may opt for typing it as non-nullable since in practice that'll often be safe:

```ts
@query('#first')
first: HTMLDivElement!;
```

The API docs should be updated to reflect one of the two patterns. The former is safer, the latter is more terse.

### Reproduction

From API docs:

```ts
class MyElement {
@query('#first')
first: HTMLDivElement;

render() {
return html`



`;
}
}
```

### Workaround

Use a pattern above

### Is this a regression?

No or unsure. This never worked, or I haven't tried before.

### Affected versions

Latest

### Browser/OS/Node environment

Any

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the linked query decorator API documentation and inspect the TypeScript example showing the uninitialized `first` property. Update the example to use one of the type-safe nullable or non-nullable patterns proposed in the issue, then verify that the displayed code type-checks.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.