0 day streak
javascript / beginner
Snippet

Checking Primitive Value Types with Typeof in Vue

The JavaScript typeof operator returns a string representing the primitive data type of an operand (e.g., 'string', 'number', 'boolean'). In Vue applications, using typeof helps inspect reactive inputs and prevent unexpected type coercion bugs.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script setup>
import { ref } from 'vue';
const rawInput = ref('42');
const typeFeedback = ref('');
function inspectInputType() {
const value = rawInput.value;
if (typeof value === 'string') {
typeFeedback.value = 'Input is currently stored as text (string).';
} else {
typeFeedback.value = 'Input is stored as another data type.';
}
}
</script>
vue
Breakdown
1
const value = rawInput.value;
Extracts the primitive value from the Vue reactive ref.
2
if (typeof value === 'string') {
Checks whether the operand data type is primitive string using typeof.
3
typeFeedback.value = '...';
Updates the reactive feedback message based on the type check outcome.