The argument of type <Interface> is not assignable to the parameter of type Record<string, string>

This error message indicates that you are trying to pass an argument of type Interface to a function or method that expects a value of type Record<string, string>. See how to fix this.

December 30, 2022 typescript

Problem

1
interface Person {
2
name: string;
3
email: string;
4
}
5
6
function logRecord(record: Record<string, string>): void {
7
/* ... */
8
}
9
10
const me: Person = {
11
name: "John",
12
email: "john@doe.com",
13
};
14
15
logRecord(me); // error: "The argument of type 'Person' is not assignable to the parameter of type 'Record<string, string>'"
16
const dictionary: Record<string, string> = me; // error: "The argument of type 'Person' is not assignable to the parameter of type 'Record<string, string>'"

Solution #1: Use type instead of interface

1
type Person = {
2
name: string;
3
email: string;
4
};
5
6
function logRecord(record: Record<string, string>): void {
7
/* ... */
8
}
9
10
const me: Person = {
11
name: "John",
12
email: "john@doe.com",
13
};
14
15
logRecord(me); // works
16
const dictionary: Record<string, string> = me; // works

Solution #2: Create a shadow copy with decomposition

1
interface Person {
2
name: string;
3
email: string;
4
}
5
6
function logRecord(record: Record<string, string>): void {
7
/* ... */
8
}
9
10
const me: Person = {
11
name: "John",
12
email: "john@doe.com",
13
};
14
15
logRecord({ ...me }); // works
16
const dictionary: Record<string, string> = { ...me }; // works

Solution #3: Use satisfies to create variable

1
interface Person {
2
name: string;
3
email: string;
4
}
5
6
function logRecord(record: Record<string, string>): void {
7
/* ... */
8
}
9
10
const me = {
11
name: "John",
12
email: "john@doe.com",
13
} satisfies Person;
14
15
logRecord(me); // works
16
const dictionary: Record<string, string> = me; // works

Solution #4: Use as keyword

1
interface Person {
2
name: string;
3
email: string;
4
}
5
6
function logRecord(record: Record<string, string>): void {
7
/* ... */
8
}
9
10
const me: Person = {
11
name: "John",
12
email: "john@doe.com",
13
};
14
15
logRecord(me as unknown as Record<string, string>); // works
16
const dictionary: Record<string, string> = me as unknown as Record<string, string>; // works

What to choose?

If you can, try to change interface into type. It is the best solution at this moment. Resolving the problem with a shadow copy has an impact on runtime execution code so is not recommended (if you do not need to create a shadow copy because of JavaScript, do not do it).

Do you like the content?

Your support helps me continue my work. Please consider making a donation.

Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are accepted.

Leave a comment