在Typescript中,如何使函数参数成为使用两个函数(一种类型)或void的泛型对象

在Typescript中,如何使函数参数成为使用两个函数(一种类型)或void的泛型对象,typescript,typescript-typings,Typescript,Typescript Typings,我在typescript中有以下情况: 我理解为什么会发生此错误(U是单一类型,但函数有两种不同的类型,它们不能合并等等),但我如何解决此问题?我需要: 严格的类型,因此不应该有any类型 允许两个函数只使用一种类型,或在一个或两个函数中使用void数字和字符串作为返回类型是不允许的 是否可以使用typescript类型系统?您可以使用: () 编辑 如果我理解正确,那么这可能会有帮助: type Matcher<T, U> = { First: (arg: T) =

我在typescript中有以下情况:

我理解为什么会发生此错误(
U
是单一类型,但函数有两种不同的类型,它们不能合并等等),但我如何解决此问题?我需要:

  • 严格的类型,因此不应该有
    any
    类型
  • 允许两个函数只使用一种类型,或在一个或两个函数中使用
    void
    <代码>数字和字符串作为返回类型是不允许的
是否可以使用typescript类型系统?

您可以使用:

()


编辑 如果我理解正确,那么这可能会有帮助:

type Matcher<T, U> = {
    First: (arg: T) => U;
    Second: () => U;
};

type MatcherOne<T, U> = {
    First: (arg: T) => void;
    Second: () => U;
};

type MatcherTwo<T, U> = {
    First: (arg: T) => U;
    Second: () => void;
};

class Main<T> {
    constructor(private value: T) { }

    match<U>(matcher: Matcher<T, U>): U;
    match<U>(matcher: MatcherOne<T, U>): U | void;
    match<U>(matcher: MatcherTwo<T, U>): U | void;
    match<U>(matcher: Matcher<T, U> | MatcherOne<T, U> | MatcherTwo<T, U>): U | void {
        return this.value
            ? matcher.First(this.value)
            : matcher.Second();
    }
}
类型匹配器={
第一:(arg:T)=>U;
第二:()=>U;
};
类型匹配器={
第一:(arg:T)=>void;
第二:()=>U;
};
类型匹配two={
第一:(arg:T)=>U;
第二:()=>无效;
};
班长{
构造函数(私有值:T){}
match(matcher:matcher):U;
匹配(匹配者:匹配者):U |无效;
匹配(matcher:MatcherTwo):U | void;
匹配(matcher:matcher | MatcherOne | MatcherTwo):U | void{
返回此.value
?匹配器优先(此值)
:matcher.Second();
}
}

()

它仍然抱怨无法从用法推断类型参数。添加了一个指向符合要求的游乐场版本的链接。这可能是一些误解。我希望matcher中的两个函数都能够是void或相同的类型。所以我刚刚在第一个和第二个函数中添加了
void
作为第二个类型,但它无法编译。那么现在可以了吗?或者您仍然有问题吗?我需要一个对象,允许用户发送对象
{First:void,Second:number}
{First:string,Second:void}
{First:array,Second:array}
,因此仅在
Second
First
函数上启用
void
是不够的。
The type argument for type parameter 'U' cannot be inferred from the usage. Consider specifying the type arguments explicitly. 
Type argument candidat 'void' is not a valid type argument because it is not a supertype of candidate 'number'.
type Matcher<T, U> = {
    First: (arg: T) => U;
    Second: () => U | void
};
match<U>(matcher: Matcher<T, U>): U | void {
    return this.value
        ? matcher.First(this.value)
        : matcher.Second();
}
type Matcher<T, U> = {
    First: (arg: T) => U;
    Second: () => U;
};

type MatcherOne<T, U> = {
    First: (arg: T) => void;
    Second: () => U;
};

type MatcherTwo<T, U> = {
    First: (arg: T) => U;
    Second: () => void;
};

class Main<T> {
    constructor(private value: T) { }

    match<U>(matcher: Matcher<T, U>): U;
    match<U>(matcher: MatcherOne<T, U>): U | void;
    match<U>(matcher: MatcherTwo<T, U>): U | void;
    match<U>(matcher: Matcher<T, U> | MatcherOne<T, U> | MatcherTwo<T, U>): U | void {
        return this.value
            ? matcher.First(this.value)
            : matcher.Second();
    }
}