【问题标题】:Typescript type function without specifying params没有指定参数的打字稿类型函数
【发布时间】:2022-01-23 04:05:28
【问题描述】:
我正在寻找一种通过返回类型松散定义函数的类型
我可以把我的类型写成
type FunctType = (...param:string[]) => RouteLocationRaw
这将允许零+字符串参数并强制函数返回RouteLocationRaw。
不过,理想情况下,我会接受任何带有任何参数的函数,只要它返回 RouteLocationRaw。
这可能吗?
【问题讨论】:
标签:
typescript
vue-router
【解决方案1】:
是的,通过使用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