不指定参数的打字稿类型函数

Typescript type function without specifying params

我希望通过 return 类型

定义一个松散定义函数的类型

我可以把我的类型写成

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

这将允许零+字符串参数并强制执行函数 return RouteLocationRaw.

理想情况下,我会接受任何带有任何参数的函数,只要它 returns RouteLocationRaw.

这可能吗?

是的,通过使用 any[] 作为其余参数类型:

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

your previous question 推断 RouteLocationRaw:

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