繁体   English   中英

错误TS2322:输入'{id:string; ''不能赋值为'ApiModelFilter <M>'

[英]error TS2322: Type '{ id: string; }' is not assignable to type 'ApiModelFilter<M>'

我尝试定义一些过滤器,其中过滤器对象的键应该是从Model接口扩展的任何接口的键。

模型接口仅定义id属性。

当我尝试在通用类中使用ApiModelFilter类型时,只需将id和字符串定义为值,我就从标题中获取错误。

我有什么想法可以解决这个问题?

我用Typescript v2.8.3和v2.6.2得到了这个错误

interface Model {
  id: number;
}

export type ApiModelFilter<M extends Model> = {
  [P in keyof M]?: string
};

interface SomeModel extends Model {
  name: string;
  age: number;
  address: string;
}

class GenericModelHandlerClass<M extends Model> {
  get_instance(id: number): void {
    const the_filter: ApiModelFilter<M> = {
      id: 'test'
    };
    ...
  }
}

class SomeModelHandlerClass extends GenericModelHandlerClass<SomeModel> {
  ...
}

嗯,看起来像一个TypeScript错误(或至少是一个设计限制)。 它与Microsoft / TypeScript#13442有关 ,其中有人感到惊讶的是,没有额外属性的Partial<U>类型的对象文字不能分配给Partial<T> ,其中T extends U 现在在这种情况下,它不是一个错误:对于某些KT[K]可能比U[K]窄,所以你不能将Partial<U>分配给Partial<T> 这不是关键问题; 这是价值观。

但是,在您的情况下,您不关心T[K]U[K]等值类型。 所有你关心的都是钥匙 如果T extends U ,它肯定似乎是类型{[K in keyof U]?: string}的字面值,没有额外的属性应该可以分配给类型{[K in keyof T]?: string}的变量。 keyof U不能包含keyof T不存在的任何值,因此它应该有效。 (在你的代码中, M的行为与T类似,而Model的行为与U类似。)由于某种原因,编译器无法验证。 如果您认为此用例引人注目,您可能希望在GitHub中提出问题


所以,解决方法。 一种方法是做一个类型断言:

const the_filter = {
  id: 'test'
} as ApiModelFilter<M>; // works

你说你比编译器更清楚,在这种情况下似乎是正确的。

或者您可以像这样重新排列代码:

const the_filter: ApiModelFilter<M> = {};
the_filter.id = 'test'; // also works

在这里,您最初将一个空对象分配给the_filter ,然后the_filter添加一个id属性。 编译器确实认识到the_filter具有可选的id属性,因此它允许您设置它。


希望其中一个适合你。 祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM