[英]Typescript cannot assign object literal to a generic type
I get a type error if I try to use an object literal with a generic type that has a type constraint, I am struggling to figure out why:如果我尝试使用具有类型约束的泛型类型的对象文字,我会收到类型错误,我正在努力找出原因:
type WithKey = {
readonly akey: string;
}
function listOfThings<T extends WithKey>(one: T) {
// This is ok
const result2: Array<T> = [one];
//This errors with Type '{ akey: string; }' is not assignable to type 'T'.
const result: Array<T> = [{ akey: 'foo' }];
return result;
}
The reason it doesn't accept { akey: 'foo' }
is because T
only extends WithKey
, so an object which is literally WithKey
isn't necessarily assignable to T
.它不接受
{ akey: 'foo' }
的原因是因为T
只扩展了WithKey
,所以字面上是WithKey
的对象不一定可以分配给T
。 For example:例如:
listOfThings<{ akey: string; aflag: boolean }>()
{ akey: 'foo' }
does not satisfy { akey: string; aflag: boolean }
{ akey: 'foo' }
不满足{ akey: string; aflag: boolean }
{ akey: string; aflag: boolean }
. { akey: string; aflag: boolean }
。
You could coerce the compiler using an assertion:您可以使用断言强制编译器:
const result: Array<T> = [{ akey: 'foo' } as T];
But this is opening you up for a bug, as in the first example would compile but not be true at runtime.但这会给您带来错误,因为在第一个示例中会编译但在运行时不是真的。 It seems like either this isn't what you want, or the types don't describe what you want.
似乎这不是您想要的,或者类型没有描述您想要的。
{ akey: 'foo' }
actually has type, it is not generic type. { akey: 'foo' }
实际上有类型,它不是泛型类型。 That's why it doesn't like your assignment.这就是为什么它不喜欢你的任务。
compiler does not understand { akey: 'foo' }
as WithKey type.编译器无法将
{ akey: 'foo' }
理解为 WithKey 类型。
you can force typescript by casting for this assignment您可以通过为此作业进行强制转换来强制打字稿
const result: Array<T> = [<T>{ akey: 'foo' }];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.