Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading