首页 > 解决方案 > 打字稿不能将对象文字分配给泛型类型

问题描述

如果我尝试将对象文字与具有类型约束的泛型类型一起使用,则会出现类型错误,我正在努力找出原因:

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;
}

标签: typescript

解决方案


它不接受的原因{ akey: 'foo' }是因为T只有extends WithKey,所以字面上的对象WithKey不一定可以分配给T. 例如:

listOfThings<{ akey: string; aflag: boolean }>()

{ akey: 'foo' }不满足{ akey: string; aflag: boolean }

您可以使用断言强制编译器:

const result: Array<T> = [{ akey: 'foo' } as T]; 

但这会为您打开一个错误,因为在第一个示例中会编译但在运行时不是真的。似乎这不是您想要的,或者类型没有描述您想要的。


推荐阅读