【发布时间】:2017-06-14 01:50:20
【问题描述】:
我在打字稿中有以下情况:
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 方法。该对象应包含两个函数:First 和 Second。该函数返回一种类型的值(例如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类型 - 允许两个函数只使用一种类型,或者
void在一个或两个中使用。number和string作为返回类型是不允许的。
是否可以使用 typescript 类型系统?
【问题讨论】:
标签: typescript typescript-typings