DEV Community

Manish Kumar
Manish Kumar

Posted on

Building Type-Safe Multi-Facet Search in Vue 3: Converting LanguageFilter to TypeScript

In community-driven open-source portals like GitLab, developers explore issues based on their technical skills—whether they write Go, Ruby, Vue/TypeScript, or Python. Providing clean, multi-select search facets allows contributors to filter hundreds of opportunities down to the exact technologies they care about.

In my recent contribution to GitLab's Contributors Platform (MR !3198), I converted the LanguageFilter component and its test suite to strict TypeScript.

Here is a look at building type-safe multi-select filters in Vue 3, managing two-way array state, and ensuring robust test coverage.


1. Multi-Select State: Moving Beyond Primitive Models

Single-value inputs (like text boxes or radio buttons) usually bind to string or number. However, multi-select facet filters manage dynamic string arrays (string[]).

Previously, LanguageFilter.vue used generic runtime options:

<!-- Before (JavaScript) -->
<script setup>
defineProps({
  availableLanguages: {
    type: Array,
    required: true,
  },
});

const selectedLanguages = defineModel('selectedLanguages', {
  type: Array,
  required: true,
});
</script>
Enter fullscreen mode Exit fullscreen mode

While this validated that the prop was an Array, it did not enforce the element type of the array. Passing an array of numbers, objects, or null values would satisfy runtime validation but cause rendering glitches in the dropdown chips.


2. Compile-Time Type Safety with Vue 3.4 Macros

By converting to <script setup lang="ts">, we typed both the available options and the reactive selection collection:

<!-- After (TypeScript) -->
<script setup lang="ts">
import { BFormGroup } from 'bootstrap-vue-next';
import VueSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';

// Strictly typed array of language names (e.g. ['Ruby', 'Go', 'Vue'])
defineProps<{
  availableLanguages: string[];
}>();

// Strongly typed two-way model binding
const selectedLanguages = defineModel<string[]>('selectedLanguages', {
  required: true,
});
</script>

<template>
  <BFormGroup label="Language">
    <VueSelect
      v-model="selectedLanguages"
      multiple
      :options="availableLanguages"
    >
      <template #no-options="{ search, searching }">
        <template v-if="searching">
          No issues in {{ search }}
        </template>
        <template v-else>
          No languages available
        </template>
      </template>
    </VueSelect>
  </BFormGroup>
</template>
Enter fullscreen mode Exit fullscreen mode

Key Benefits:

  • Element-Level Type Safety: Both availableLanguages and selectedLanguages are guaranteed to be string[]. The compiler flags any attempt to push non-string entities.
  • Named Two-Way Model: defineModel<string[]>('selectedLanguages', { required: true }) creates a contract where the parent must bind v-model:selectedLanguages, automatically typing the event payload for update:selectedLanguages.

3. Strict Event and Slot Testing with Vitest

In LanguageFilter.spec.ts, we eliminated loose typing in test helpers and refined emitted event assertions:

import type { VueWrapper } from '@vue/test-utils';
import { shallowMount } from '@vue/test-utils';
import VueSelect from 'vue-select';
import LanguageFilter from './LanguageFilter.vue';

describe('LanguageFilter', () => {
  const defaultProps = {
    availableLanguages: ['Ruby', 'Go'],
    selectedLanguages: [],
  };

  let wrapper: VueWrapper;
  const createWrapper = (props = {}) =>
    wrapper = shallowMount(LanguageFilter, {
      props: { ...defaultProps, ...props },
      global: { renderStubDefaultSlot: true },
    });

  const findSelect = () => wrapper.findComponent(VueSelect);

  // Safe helper to render the child component's custom no-options slot
  const findNoOptions = (slotProps: Record<string, unknown>) =>
    shallowMount({
      render: () => findSelect().vm.$slots['no-options']?.(slotProps),
    });

  it('emits updated language selection when an option is picked', async () => {
    createWrapper();

    await findSelect().vm.$emit('update:modelValue', ['Ruby']);

    // Checking exact emit structure: [[['Ruby']]]
    expect(wrapper.emitted('update:selectedLanguages')).toEqual([[['Ruby']]]);
  });

  it('renders helpful message when searched language has no issues', () => {
    createWrapper();

    const noOptionsWrapper = findNoOptions({ search: 'Haskell', searching: true });
    expect(noOptionsWrapper.text()).toContain('No issues in Haskell');
  });
});
Enter fullscreen mode Exit fullscreen mode

Notice the event assertion:

expect(wrapper.emitted('update:selectedLanguages')).toEqual([[['Ruby']]]);
Enter fullscreen mode Exit fullscreen mode

Rather than asserting wrapper.emitted('update:selectedLanguages')[0], matching the entire emitted event array verifies both the payload and the exact call count in a single check.


Key Takeaways

  1. Type Array Elements, Not Just Array: In TypeScript SFCs, always specify string[] or T[] rather than generic Array to prevent bad data downstream.
  2. Harmonize Filter Facet APIs: Keeping filter components uniform (LanguageFilter, ProjectFilter) with consistent named models (selectedLanguages, selectedProjects) makes parent filter bars clean and modular.
  3. Full Event Array Assertions: In Vue Test Utils, asserting against the entire emitted event array (expect(wrapper.emitted('event')).toEqual([[payload]])) guards against unexpected duplicate emissions.

Check out the merged Merge Request on GitLab:

👉 GitLab Contributors MR !3198


Author: Manish Kumar

GitLab: @manishpatel00

Top comments (0)