3

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);
4
  • 2
    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 Commented Mar 13, 2021 at 13:05
  • 1
    Or accept any type with a toString method (should be everything) toStr(i: {toString(): string}): string Commented Mar 13, 2021 at 14:03
  • 2
    @LindaPaiste technically not everything will have toString (e.g. Object.create(null)), but typescript can't catch this Commented Mar 14, 2021 at 5:36
  • The point is eslint complains when you use the object type. Commented Apr 7, 2021 at 6:50

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.