gpt4 book ai didi

typescript :函数重载

转载 作者:搜寻专家 更新时间:2023-10-30 21:08:51 25 4
gpt4 key购买 nike

在 TypeScript 中实现/实现此类函数重载的最简单方法是什么?

function Foo(
param1: number,
param2: string,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void { .... }

function Foo(
param6: number,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void { .... }

最佳答案

它包含在 Overloads section of the Functions docs 中,但在您的情况下可能是这样的:

function Foo(
param1: number,
param2: string,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void;
function Foo(
param6: number,
param3: string,
param4: () => void,
param5: (xyz: string) => void): void;

function Foo(...args: any[]): void {
if (args.length === 5) {
// 1st signature
} else if (args.length === 4) {
// 2nd signature
} else {
// error: unknown signature
}
}

( code in playground )

关于 typescript :函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38480929/

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