Last active
September 14, 2018 23:23
-
-
Save tommysullivan/bdd188673adcd8e6ad4c3db3aefc0720 to your computer and use it in GitHub Desktop.
narrowing filter example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[23:21:45] File change detected. Starting incremental compilation... | |
src/models/District.ts:73:7 - error TS2322: Type '(item: General) => boolean' is not assignable to type '(item: General) => item is Specific1'. | |
Signature '(item: General): boolean' must be a type predicate. | |
73 const predicate3:(item:General) => item is Specific1 = item => item.kind=="Specific1"; | |
~~~~~~~~~~ | |
src/models/District.ts:76:65 - error TS2345: Argument of type '(item: General) => boolean' is not assignable to parameter of type 'TypePredicate<General, General>'. | |
Signature '(item: General): boolean' must be a type predicate. | |
76 const listOfOnlySubtypes2 = narrowingFilterFunction(unfiltered, predicate2) | |
~~~~~~~~~~ | |
[23:21:46] Found 2 errors. Watching for file changes. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export type TypePredicate<U extends T, T> = (item:T) => item is U; | |
export type NarrowingFilterSignature = <U extends T, T>(items:T[], predicate:TypePredicate<U, T>) => U[]; | |
export type General = Specific1 | Specific2; | |
export interface Specific1 { | |
kind: "Specific1", | |
specific1OnlyMethod():void, | |
} | |
export interface Specific2 { | |
kind: "Specific2", | |
specific2OnlyMethod():void, | |
} | |
declare const unfiltered:General[]; | |
declare const narrowingFilterFunction:NarrowingFilterSignature; | |
function predicate1(item:General): item is Specific1 { | |
return item.kind=="Specific1"; | |
} | |
function predicate2(item:General) { | |
return item.kind=="Specific1"; | |
} | |
const predicate3:(item:General) => item is Specific1 = item => item.kind=="Specific1"; | |
const listOfOnlySubtypes1 = narrowingFilterFunction(unfiltered, predicate1) | |
const listOfOnlySubtypes2 = narrowingFilterFunction(unfiltered, predicate2) | |
const listOfOnlySubtypes3 = narrowingFilterFunction(unfiltered, predicate3) | |
listOfOnlySubtypes1[0].specific1OnlyMethod(); | |
listOfOnlySubtypes2[0].specific1OnlyMethod(); | |
listOfOnlySubtypes3[0].specific1OnlyMethod(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment