Typescript type function without specifying params

I’m looking to define a type that loosely defines a function by return type

I could write my type as

type FunctType = (...param:string[]) => RouteLocationRaw

Which would allow for zero+ string params and enforce that the function return RouteLocationRaw.

Ideally though, I would accept any function with any params, as long as it returns RouteLocationRaw.

Is this possible?

>Solution :

Yes, by using any[] as the rest parameter type:

type Acceptable = (...args: any[]) => RouteLocationRaw;

Inferring RouteLocationRaw from your previous question:

TS Playground

import {type RawLocation as RouteLocationRaw} from 'vue-router';

type Fn<
  Params extends unknown[] = any[],
  Result = any,
> = (...params: Params) => Result;

type Acceptable = Fn<any[], RouteLocationRaw>;

declare const loc: RouteLocationRaw;

const fn1: Acceptable = () => loc;
const fn2: Acceptable = (p1: string) => loc;
const fn3: Acceptable = (p1: string, p2: number) => loc;
const fn4: Acceptable = () => 42; // error
const fn5: Acceptable = () => ['hello']; // error

Leave a Reply