Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript: cannot cast down to generic "Record<string, string>" type?

Tags:

typescript

Why won't typescript allow me to cast the following:

interface foo {
  foofoo: string
  feefee: string
  faafaa: 'red' | 'blue'
}

into Record<string, string> ? How do I make that happen?

I've tried:

  • changing the string literals red|blue to just string type
  • tried instanceOfFoo as Record<string, string>
  • tried changing it into a type instead of an interface

...no joy whatsoever any help appreciated

like image 537
yen Avatar asked May 22 '26 12:05

yen


1 Answers

TypeScript signals an error here not because the two types are not assignable to one another, but because they have no properties in common, this is almost always made by mistake, and the instruction on the error is fairly clear on what to do in the case that is not.

Conversion of type 'foo' to type 'Record' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

Emphasis mine.

So what you need to do is something like

declare const x: foo; // there exists a variable x of type foo.
const y = x as unknown as Record<string, string>; // cast to unknown, then to Record.

Playground link

like image 153
Madara's Ghost Avatar answered May 25 '26 03:05

Madara's Ghost