【发布时间】:2020-05-08 12:56:19
【问题描述】:
我正在尝试使用具有泛型返回类型的重载函数的联合类型,当元组类型作为泛型传递时,TypeScript 似乎丢失了:
type Fn1<R> = (one: string) => R;
type Fn2<R> = (one: string, two: string) => R;
type Fn3<R> = (one: string, two: string, three: string) => R;
type GenericOverloadingFn<R> = Fn1<R> | Fn2<R> | Fn3<R>;
type TupleOfPrimitives = [
string,
number
];
type StructWithKeys = {
one: string;
two: number;
}
type UnionFn = GenericOverloadingFn<TupleOfPrimitives>
| GenericOverloadingFn<string>
| GenericOverloadingFn<StructWithKeys>;
type UnionGenericFn = GenericOverloadingFn<
TupleOfPrimitives
| string
| StructWithKeys
>;
const union2Fn0: UnionFn = (one: string, two: string) => "hey"; // works
const union2Fn1: UnionFn = (one: string, two: string) => ({ one: "hey", two: 1 }); // works
const union2Fn2: UnionFn = (one: string, two: string) => ["hey", 2]; // error
const union1Fn0: UnionFn = (one: string) => ["hey", 2]; // error
const union3Fn0: UnionFn = (one: string, two: string, three: string) => ["hey", 2]; // works
const unionGeneric2Fn0: UnionGenericFn = (one: string, two: string) => "hey"; // works
const unionGeneric2Fn1: UnionGenericFn = (one: string, two: string) => ({ one: "hey", two: 1 }); // works
const unionGeneric2Fn2: UnionGenericFn = (one: string, two: string) => ["hey", 2]; // error
const unionGeneric3Fn2: UnionGenericFn = (one: string, two: string, three: string) => ["hey", 2]; // works
const fn20: Fn2<TupleOfPrimitives> = (one: string, two: string) => ["hey", 2]; // works
const fn21: Fn2<string | TupleOfPrimitives> = (one: string, two: string) => "hey"; // works
const fn22: Fn2<string | TupleOfPrimitives> = (one: string, two: string) => ["hey", 2]; // works
const genericOverloading2Fn: GenericOverloadingFn<TupleOfPrimitives> =
(one: string, two: string) => ["hey", 2]; // error
const genericOverloading3Fn: GenericOverloadingFn<TupleOfPrimitives> =
(one: string, two: string, three: string) => ["hey", 2]; // works
错误大多是这样的
Type '(one: string, two: string) => (string | number)[]' is not assignable to type 'UnionFn'.
Type '(one: string, two: string) => (string | number)[]' is not assignable to type 'Fn1<TupleOfPrimitives>'.
我不确定是做错了什么还是 TypeScript 的限制/错误?
【问题讨论】:
标签: typescript generics types tuples