I would like to improve the type function of the section in my TS library.
Applying it to Array, type:
function partition<T>(list: T[], predicate:(x:T)=>boolean): [T[],T[]];
And an example call would be:
[1,2,3,4].partition(x => x%2===0)
=> [[2,4],[1,3]]
Typescript 2.8 now adds conditional types , and in particular Exclude (note that typescript 2.8 is only at the stage of selecting a release).
So, my idea is to improve the type of the section so that you can use the type protection functions, would be this:
function partition<T>(list: T[], predicate:(x:T)=>boolean): [T[],T[]];
function partition<T,U extends T>(list: T[], predicate:(v:T)=>v is U): [U[],Array<Exclude<T,U>>];
Unfortunately, I cannot get this to compile with --stricttypescript 2.8rc.
Here is an example program:
function partition<T>(list: T[], predicate:(x:T)=>boolean): [T[],T[]];
function partition<T,U extends T>(list: T[], predicate:(v:T)=>v is U): [U[],Array<Exclude<T,U>>];
function partition<T,U extends T>(list: T[], predicate:(v:T)=>v is U): [U[],Array<Exclude<T,U>>] {
return <any>[];
}
Compile with TS 2.8rc with --strictto reproduce the build error:
test.ts(2,10): error TS2394: Overload signature is not compatible with function implementation.
Exclude, [T[],T[]], [T[], Array<T|never>>], , .
, , typescript 2.8?
Titian Cernicova-Dragomir , , - :
class Vector<T> {
partition<U extends T>(predicate:(v:T)=>v is U): [Vector<U>,Vector<Exclude<T, U>>];
partition(predicate:(x:T)=>boolean): [Vector<T>,Vector<T>];
partition<U extends T>(predicate:(v:T)=>boolean): [Vector<U>,Vector<Exclude<T, U>>] {
return <any>[];
}
}
, - , , ...
:
class Vector<T> {}
function partition<T,U extends T>(list: Vector<T>, predicate:(v:T)=>v is U): [Vector<U>,Vector<Exclude<T, U>>];
function partition<T>(list: Vector<T>, predicate:(x:T)=>boolean): [Vector<T>,Vector<T>];
function partition<T,U extends T>(list: Vector<T>, predicate:(v:T)=>boolean): [Vector<U>,Vector<Exclude<T, U>>] {
return <any>[];
}
...