Is it possible to create a reusable TypeScript interface for an array of functions?

Currently working with Vue and Typescript, I'm exploring different ways to describe types for an array of functions. In my current code, I have the following setup. Is there a way I could define an interface called formRules instead of repeatedly declaring the types

Array<(v: string) => boolean | string>
or just
<(v: string) => boolean | string>
?

<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';

@Component({
  name: 'signUpForm',
})

export default class SignUpForm extends Vue {
  private valid = true

  private firstName = ''
  private lastName = ''
  private nameRules: Array<(v: string) => boolean | string> = [
    (v) => !!v || 'Name is required',
  ]

  private email = ''
  private emailRules: Array<(v: string) => boolean | string> = [
    (v) => !!v || 'E-mail is required',
    (v) => /.+@.+\..+/.test(v) || 'E-mail must be valid',
  ]
}
</script>

Answer №1

interface ValidateInput={(value:string):boolean|string}

type ValidateMultipleInputs=ValidateInput[]


let validationRules:ValidateInput[]
//or
let validationRulesArr:ValidateMultipleInputs

Answer №2

Define a custom type that matches your function signature.

<script lang="ts>
import { Vue, Component } from 'vue-property-decorator';

@Component({
  name: 'signUpForm',
})

type FormValidator = (value: string) => boolean | string;

export default class SignUpForm extends Vue {
  private valid = true

  private firstName = ''
  private lastName = ''
  private nameRules: FormValidator[] = [
    (value) => !!value || 'Name is required',
  ]

  private email = ''
  private emailRules: FormValidator[]*emphasized text* = [
    (value) => !!value || 'E-mail is required',
    (value) => /.+@.+\..+/.test(value) || 'E-mail must be valid',
  ]
}
</script>

Note that TypeScript can infer the types automatically, so specifying them may not be necessary. Just specify the type for the parameter if needed:

export default class SignUpForm extends Vue {
  private valid = true

  private firstName = ''
  private lastName = ''
  private nameRules = [
    (value: string) => !!value || 'Name is required',
  ]

  private email = ''
  private emailRules = [
    (value: string) => !!value || 'E-mail is required',
    (value: string) => /.+@.+\..+/.test(value) || 'E-mail must be valid',
  ]
}

This approach is cleaner and avoids unnecessary type definitions.

Answer №3

Let's consider a basic illustration-


const array: ((val: string) => boolean | string)[];
let elements: array;
elements = [(val: string) => val];
console.log(elements[0]("hello"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting up a bi-directional binding to an empty or new object that is a valid reference

What is the proper way to set up binding to a class object with all properties valid but empty? Success...If the component is defined like this: export class BioComponent implements OnInit { bio : Bio = { id : 1, FirstName : "", LastName : ""}; con ...

Send a variable from a next.js middleware to an API request

I've been attempting to pass a middleware variable to my API pages via "req" but have encountered some issues Even after trying to send the user token to pages using "req", it consistently returns null The middleware file in question is: pages/api/u ...

What could be causing my date variable to reset unexpectedly within my map function?

Currently, I'm utilizing a tutorial to create a custom JavaScript calendar and integrating it into a React project You can find the functional JavaScript version in this jsfiddle import { useState, useRef, useMemo } from 'react' import type ...

What is the process for sending an email using Angular 6 and ASP.NET CORE web api?

When a user inputs their email and password in the designated boxes, they also include a recipient email address with a CC. This information is then sent via a web api. The email will contain text like "Total Sales Today" along with an attached PDF file. ...

What is the best method for dividing a user interface into several arrays of keys, each grouped by type?

Given a simple structure: structure IPerson { firstName: string; lastName: string; age: number; city: string; favoriteNumber: number; isMarried: boolean; hasDriverLicense: boolean; } How do I create arrays containing keys grouped by data typ ...

Nest JS Guards - Employ either of two approaches

I have implemented two different JWT based strategies in my application: The first strategy involves single sign-on for organization members, where an external provider generates a JWT. The second strategy is for email/password authenticated external user ...

5 steps to effectively filter child items in Vuetify

I am using a drawer in my Vuetify project that contains a dropdown menu. I'm trying to access specific children items within the dropdown based on permission. Currently, it filters all contents in the dropdown menu but I want to filter only certain ch ...

The operation failed with a TypeError because the object does not allow the addition of the newField property

I encountered an error that says: TypeError: Cannot add property newField, object is not extensible Whenever I try to add a new key or change a value, it doesn't work and I'm not sure what the issue is. dynamicFilter; public ionViewWillEnte ...

Calculate the overall cost from an array of information using Vue.js and Laravel

In a view, I have fields for selecting from and to dates along with branch and spare parts as dropdown options. When I select the date range, it will retrieve data including the branch name, grand total, etc. What I am trying to achieve is getting the tota ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

The Vue.js application using pinia npm encounters a server error due to a variable being assigned a value but never utilized

I found this helpful video tutorial on how to fix that pesky error in my code, but I keep encountering the message: "error 'counter' is assigned a value but never used no-unused-vars". Can anyone point out what I might be overlooking? <temp ...

Implementing multiple components in a Vue route: A comprehensive guide

As a beginner in Vue, I am experimenting with incorporating two components in a route - a navigation bar and some sales data. The assets are being bundled by Laravel mix using Webpack, but I keep encountering failures with npm. index.php <body> ...

Facing issues with vertical Tab display in Bootstrap using Vue.js - unexpected results

Below is the script I am working with: <vue-tabs class="row" direction="vertical" value="Description"> <div v-for="(siteParts, index) in sitePartLine"> <v-tab :title="sitePartLine[index].serial_no" v-if="sitePartLine[i ...

Launching a Material UI Modal nested within a parent component

I have a table displaying various teams. Each row in the table has a menu option that, when clicked, should open either a modal or a dialog box. I want to keep the table, menu functionality, and modals as separate components for better organization. Here&a ...

What is the best way to retrieve the updated input value in Vue?

I am working with a dates object that gets passed to a component, and I need to update the list when a new date is clicked. I believe using a computed property to set the date is the way to go. I initially tried using data, but the value wouldn't chan ...

Using Vue.js to transform a map filter into a variable

const managers = new Map([ ['<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6221235353535322060d0f030b0c4c010d0f">[email protected]</a>', '<a href="/cdn-cgi/l/email-protection" class="__cf_e ...

Is it possible to optimize the performance of my React and TypeScript project with the help of webpack?

I am working on a massive project that takes 6 to 8 minutes to load when I run npm start. Is there a way to speed up the loading process by first displaying the sign-in page and then loading everything else? ...

Guidelines for implementing grpc-web in a Vue.js application

Currently, I am attempting to integrate a grpc-web client into my Vue application with the following code: import Vue from "vue"; import App from "./App.vue"; const { Registration, _ } = require("./identity-service_pb.js"); const { IdentityServicePromis ...

Implementing the Same Vue Component with Different Path Names

Is there a more efficient way to have different URLs (Consumer and Seller) for the same SingleProduct component? The initial method works well: const routes = [ { path: "/:name", name: "SingleProductSeller", component: SingleProduct }, { ...

Converting ASP .Net Core Dto's and Controllers into TypeScript classes and interfaces

My concept involves incorporating two key elements: Converting C# Dto's (Data-transfer-objects) into TypeScript interfaces to ensure synchronization between client-side models and server-side. Transforming ASP .Net Core controller endpoints into Typ ...