gpt4 book ai didi

TypeScript:我可以为重载的函数签名提供类型别名吗?

转载 作者:行者123 更新时间:2023-12-05 09:18:03 24 4
gpt4 key购买 nike

是否可以为重载的函数签名创建类型别名?

例如,我有这样一个函数:

function whenChanged(scope: ng.IScope, fn: ()=>void): ()=>void;
function whenChanged(fn: ()=>void, truthy:any): ()=>void;
function whenChanged(a,b): ()=>void {
//...
}

我想为重载的签名创建类型别名以节省重复,并在其他需要描述此函数类型的地方使用。

我试过:

type WC1 = (scope: ng.IScope, fn: ()=>void) => ()=>void;
type WC2 = (fn: ()=>void, truthy:any) => ()=>void;
type WhenChanged = WC1 | WC2;

const whenChanged: WhenChanged = (a,b) => {
//...
};

但是在尝试使用这个函数时,我收到了一条错误消息“无法调用类型缺少调用签名的表达式”。

我不能随手在文档中看到任何关于类型别名函数重载的内容。

最佳答案

因为您已经有了函数whenChanged:

function whenChanged(scope: ng.IScope, fn: ()=>void): ()=>void;
function whenChanged(fn: ()=>void, truthy:any): ()=>void;
function whenChanged(a,b): ()=>void {
//...
}

为其类型获取类型别名的最简单方法是使用typeof type query :

type WhenChanged = typeof whenChanged;

接下来,创建类型别名的最直接方法是使用 overloaded function signature (这正是您要找的):

type WhenChanged = {
(scope: ng.IScope, fn: () => void): () => void;
(fn: () => void, truthy: any): () => void;
}

(如果您将鼠标悬停在编辑器中的 typeof 定义上,您将在 quickinfo 中看到。)请注意,您不需要使用 interface 如果你不想。


接下来您可以做的事情与您正在做的事情类似,但问题是重载是一个交集,而不是一个并集。它是两个签名:

type WC1 = (scope: ng.IScope, fn: ()=>void) => ()=>void;
type WC2 = (fn: ()=>void, truthy:any) => ()=>void;
type WhenChanged = WC1 & WC2; // and, not or

注意intersections of function signatures are not commutative ,特别是因为它们代表重载。这意味着以下类型在技术上并不相同:

type NotWhenChanged = WC2 & WC1; // different type

因为重载决议将以不同的顺序进行。

请注意,您不能调用WC1 | 类型的函数。 WC2 由于调用签名不同,编译器无法判断函数是 WC1 还是 WC2


好的,到此为止。希望能帮助到你;祝你好运!

关于TypeScript:我可以为重载的函数签名提供类型别名吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45693612/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com