2
votes

I have a class that has some public properties and I would like to pass it to a function with a generic argument of an index interface type, but I get an compiler error that says Argument of type 'Car' is not assignable to parameter of type '{ [k: string]: unknown; }'.

Could someone explain what is wrong because I assume all Classes are of type object?!!

class Car {

  name: string | undefined;

}

function toStr <T extends { [k: string]: unknown }>(i: T) {
  return i.toString();
}


const jeep = new Car();
jeep.name = 'jeep';

toStr(jeep);
1
Car doesn't define index signature but function parameter has constraint for it. Could you explain what's the point of generics here? Both function toStr(i: object) ... and function toStr(i: Record<string, any>) ... will work - Aleksey L.
Or accept any type with a toString method (should be everything) toStr(i: {toString(): string}): string - Linda Paiste
@LindaPaiste technically not everything will have toString (e.g. Object.create(null)), but typescript can't catch this - Aleksey L.
The point is eslint complains when you use the object type. - alireza-bonab

1 Answers

1
votes

Just use object instead { [k: string]: unknown }.

class Car {

  name: string | undefined;

}

function toStr <T extends object>(i: T) {
  return i.toString();
}


const jeep = new Car();
jeep.name = 'jeep';

const result = toStr(jeep);