sasta_achar
sasta_achar

Reputation: 95

How to assign a typed function to a generic function

I am not sure if i framed the question right, basically i just want to enforce the compare function to take 2 args and i want them both to be of same type(T) and the function should return a boolean.

How can achieve something like this . I couldn't get it working, the below implementation gives the following error :

Argument of type '(a: CustomType, b: CustomType) => boolean' is not assignable to parameter of type '(a: T, b: T) => boolean'. Types of parameters 'a' and 'a' are incompatible. Type 'T' is not assignable to type 'CustomType'

function DefaultCompare<T>(a: T, b: T): boolean {
  return a > b;
}

class ClassA<T> {

    public a :T;
    public b :T;
    private compare : (a :T , b :T) => boolean;

    constructor(a : T, b: T,compare= DefaultCompare) {
        this.a = a;
        this.b = b;
        this.compare = compare;
    }
}

interface CustomType {
    cost : number,
    name : string,
}
function CustomCompare (a: CustomType, b: CustomType): boolean {
  return a.cost > b.cost;
}


const objA_1 = new ClassA<Number>(1, 2);


const _a : CustomType = { cost : 1, name : 'js'}, 
        _b : CustomType = {cost : 2, name : 'ts'};

const objA_2 = new ClassA<CustomType>(_a, _b, CustomCompare);

Playground link

Upvotes: 1

Views: 72

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

Define a type for your comparison function parameter:

type CompareFn<T> = (a: T, b: T) => boolean;

...and then use it in the compare parameter of the constructor:

constructor(a : T, b: T, compare: CompareFn<T> = DefaultCompare) {
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^

Playground link

Upvotes: 1

Related Questions