简体   繁体   English

打字稿不能将对象文字分配给泛型类型

[英]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.

相关问题 将对象文字分配给打字稿泛型类型 - Assigning an object literal to a typescript generic type 打字稿类型在使用联合类型的对象文字分配上丢失 - typescript type is lost on an object literal assign using a union type TypeScript通用类:无法分配给通用类型变量 - TypeScript Generic Classes: Cannot assign to Generic Type Variable 打字稿将泛型约束为字符串文字类型以用于计算对象属性 - Typescript constrain generic to string literal type for use in computed object property Typescript 类型为 object 字面量 - Typescript type to object literal 如何在打字稿中为对象的通用键类型分配值类型? - How assign a value type to a generic key type of an object in typescript? Typescript:为什么我们不能为泛型类型分配默认值? - Typescript: Why is it that we cannot assign default value to generic type? Typescript Generic class 和 Object.assign 看不到值 - Typescript Generic class and Object.assign cannot see the value 打字稿:一般类型被推断为文字类型 - Typescript: Generic Type being inferred to Literal Type TypeScript泛型:泛型函数类型和对象文字类型的调用签名不相等(类型&#39;T&#39;不能分配给类型&#39;T&#39;) - TypeScript generics: Inequivalence of generic function type and call signature of an object literal type (Type 'T' is not assignable to type 'T')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM