Skip to content

New rule vue/require-typed-ref: disallow ref() without type parameter or argument #2105

Closed
@Demivan

Description

@Demivan

Please describe what the rule should do:

Disallow calling ref() function without generic type parameter or an argument when using TypeScript.

With TypeScript it is easy to prevent usage of any by using no-implicit-any. Unfortunately this rule is easily bypassed with Vue ref() function. Calling ref() function without a generic parameter or an initial value leads to ref having Ref<any> type.

What category should the rule belong to?

[x] Enforces code style (layout)
[x] Warns about a potential error (problem)
[ ] Suggests an alternate way of doing something (suggestion)
[ ] Other (please specify:)

Provide 2-3 code examples that this rule should warn about:

Bad:

<script setup lang="ts">
const counter = ref() // Ref<any>

counter.value = 0
counter.value = '' // Would be caught if we had typed ref
</script>

Bad: (maybe as an option to disallow explicit any too)

<script setup lang="ts">
const counter = ref<any>() // Ref<any>
</script>

Good:

<script setup lang="ts">
const counter = ref(0) // Ref<number>

conter.value = '' // Will result in a typecheck error
</script>

Good:

<script setup lang="ts">
const counter = ref<number>()
</script>

Additional example by @FloEdelmann
Good:

<script setup lang="ts">
const counter: Ref<number | undefined> = ref()
</script>

Additional context

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions