yen
yen

Reputation: 2292

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

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:

...no joy whatsoever any help appreciated

Upvotes: 9

Views: 7926

Answers (1)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

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

Upvotes: 9

Related Questions