Allow $refs to be undefined in Typescript types
See original GitHub issueWhat problem does this feature solve?
Currently, when you add $refs
annotations to a class-based component, the types are defined as follows:
@Component
export default class Foo extends Vue {
$refs!: {
bar: Bar;
};
}
This is handy and allows you to use refs as expected in class methods:
fooMethod() {
this.$refs.bar.method();
}
However, the types incorrectly assume that the ref is always present, while it might not be so.
async fooMethod() {
await longApiRequest();
this.$refs.bar.method();
}
In the above situation, the ref would be undefined
if the component unmounted during the async request.
What does the proposed API look like?
The correct types would ideally mark refs as possibly undefined automatically, or alternatively allow the user to do so.
@Component
export default class Foo extends Vue {
$refs!: {
bar: Bar | undefined;
};
}
Currently types don’t allow this.
The above types would ensure the user correctly checks for the ref before calling a method on it:
async fooMethod() {
await longApiRequest();
this.$refs.bar?.method();
// -----------^
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (2 by maintainers)
Top Results From Across the Web
Ref object is possibly undefined TypeScript React
1 Answer 1 · This resolves the initial error but I then get "classList" does not exist on type "never" even if I...
Read more >Documentation - TypeScript 2.0
Expression operators permit operand types to include null and/or undefined but always produce values of non-null and non-undefined types.
Read more >Documentation - Advanced Types - TypeScript
By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values of every type. That...
Read more >Documentation - Do's and Don'ts - TypeScript
In cases where you don't know what type you want to accept, or when you want ... fine to pass an explicit undefined...
Read more >Documentation - TypeScript 3.7
let x = foo?.bar. · let x = foo === null || foo === undefined ? undefined : foo. · // Before. if...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
https://github.com/vuejs/vue/pull/11112
@posva Upon further inspection, the types stem from this repository, not the class component definition.
They’re defined here: https://github.com/vuejs/vue/blob/dev/types/vue.d.ts#L29
Should this ticket be reopened or is there a better course of action I can take to address this?