microsoft / microsoft/TypeScript
Refine type checking for class accessor when using decorator
Nobody has claimed this yet.
- Dominant language
- Go
- Stars
- 111k
- Forks
- 14.4k
- Avg merge
- 1d 19h
- Merged PRs (30d)
- 117
Description
Suggestion
🔍 Search Terms
decorator, class accessor, auto-accessor, types, null checks.
✅ Viability Checklist
My suggestion meets these guidelines:
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This feature would agree with the rest of TypeScript's Design Goals.
⭐ Suggestion
If a class accessor decorator will always add an initial value for the decorated accessor, TypeScript should infer that the accessor is always non-null, even if no initial value in its original declaration.
📃 Motivating Example
See playground.
The decorator dec will always initialize the accessor with a non-null value, but TS reports an error on @dec accessor data: Wrapper<string>;. It says "Property 'data' has no initializer and is not definitely assigned in the constructor" when strictNullChecks is enabled.
function dec<This, Value>(
target: ClassAccessorDecoratorTarget<This, Wrapper<Value>>,
context: ClassAccessorDecoratorContext<This, Wrapper<Value>>,
): ClassAccessorDecoratorResult<This, Wrapper<Value>> {
return {
init(initialValue) {
if (initialValue !== undefined) {
return initialValue;
}
return {};
}
}
}
interface Wrapper<T = unknown> {
value?: T;
}
class Test {
@dec accessor data: Wrapper<string>;
}
Are there any workarounds, other than putting an ! after data, to make the type checking works?
💻 Use Cases
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked TypeScript Playground example and reproduce the diagnostic under strictNullChecks for the decorated accessor. Read the decorator and class-accessor behavior described in the issue, then determine the type-checking change needed so the accessor is treated as initialized; done means the example no longer requires a non-null assertion while preserving existing runtime behavior.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- typescript
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100