2017-05-03 45 views
1

以下似乎是有效的:打字稿功能接口实现

interface IPredicate { 
    (s: Product): boolean 
    and(IPredicate): IPredicate 
    or(IPredicate): IPredicate 
} 

如果它是有效的,我怎么能实现它,以便大致有以下工作:

let a: IPredicate = (s: Something) => true 
let b: IPredicate = (s: Something) => false 
let c: IPredicate = a.and(b) 

回答

2

更详细一些:

interface IPredicate<T> { 
    (item: T): boolean 
    and(p: IPredicate<T>): IPredicate<T>; 
    or(p: IPredicate<T>): IPredicate<T>; 
} 

function createPredicate<T>(source: (item: T) => boolean) { 
    let predicate = source as IPredicate<T>; 
    predicate.and = (another:IPredicate<T>) => createPredicate((item: T) => source(item) && another(item)); 
    predicate.or = (another:IPredicate<T>) => createPredicate((item: T) => source(item) || another(item)); 

    return predicate; 
} 

type Something = {}; 

let a: IPredicate<Something> = createPredicate((s: Something) => true); 
let b: IPredicate<Something> = createPredicate((s: Something) => false); 
let c: IPredicate<Something> = a.or(b);