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:
string typeinstanceOfFoo as Record<string, string>...no joy whatsoever any help appreciated
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With