0
在我正在处理的库中,我有一种方法可以确保IList
类型的东西,如果不是,它会将其变为IList
类型的实例。请参见下面的代码:如何在TypeScript中使用泛型重载函数进行类型转换
1 import { IList, isList } from './list';
2
3 import Unit from './unit';
4 import ArrayList from './array_list';
5
6 export default function factory<V,I>(obj: IList<V,I>): IList<V,I>;
7 export default function factory<V>(obj: V[]): IList<V,number>;
8 export default function factory<V>(obj: V): IList<V,number> {
9 if(isList(obj)) return obj;
10 if(Array.isArray(obj)) return new ArrayList(obj);
11 return new Unit(obj);
12 }
这种方法编译失败,请参阅下面的错误:
src/factory.ts(9,30): 2322 Type 'V' is not assignable to type 'IList<V, number>'.
Property 'has' is missing in type '{}'.
src/factory.ts(10,51): 2345 Argument of type 'V' is not assignable to parameter of type '{}[]'.
Property 'length' is missing in type '{}'.
src/factory.ts(11,14): 2322 Type 'Unit<{}>' is not assignable to type 'IList<V, number>'.
Types of property 'get' are incompatible.
Type '(id: number) => {}' is not assignable to type '(id: number) => V'.
Type '{}' is not assignable to type 'V'.
我不能确定如何解决此问题:当然,我可以简单地声明的返回类型该方法为any
,但这是不可接受的,因为这会导致在别处输入问题。
有谁知道我应该如何继续?