[英]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>
? 到Record<string, string>
? How do I make that happen? 我如何做到这一点?
I've tried: 我试过了:
string
type 将字符串文字red | blue更改为仅string
类型 instanceOfFoo as Record<string, string>
尝试过instanceOfFoo 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. TypeScript在这里发出错误信号不是因为这两种类型不能彼此分配,而是因为它们没有共同的属性 ,这几乎总是由错误造成的,并且在错误情况下的说明非常清楚如何处理那不是。
Conversion of type 'foo' to type 'Record' may be a mistake because neither type sufficiently overlaps with the other. 从“ foo”类型到“ Record”类型的转换可能是错误的,因为这两个类型都没有足够的重叠。 If this was intentional, convert the expression to 'unknown' first . 如果这是故意的, 请先将表达式转换为'unknown' 。
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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.