如何使函数参数成为泛型对象,在Typescript

时间:2017-01-28 12:43:11

标签: typescript typescript-typings

我在打字稿中有以下情况:

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

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

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

const main = new Main(10);

const res = main.match({ // there is a problem
  First: v => v + 10,
  Second: () => console.log()
});

所以我有一个对象,用户必须传递给类实例的match方法。该对象应包含两个函数:FirstSecond。此函数返回一种类型(例如number)或一种类型+ void(例如number + void)的值,但没有别的。不能有string + number种类型。

此代码失败并出现错误

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'.

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

  • 严格打字,因此不应该有any类型
  • 仅允许两种功能使用一种类型,或者在一种或两种功能中仅使用voidnumberstring不允许返回类型。

是否可以使用打字稿类型系统?

1 个答案:

答案 0 :(得分:1)

您可以使用union types

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

我将void添加到第二个函数中,但您也可以在第一个函数中添加它。

但您需要使用match方法返回| void

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

code in playground

修改

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

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();
    }
}

code in playground