[英]Typescript: can't get generics to work with extends
I'm trying to restrict input to an object, but it fails: 我试图将输入限制为一个对象,但失败:
showModal<T extends {[key: string]: any}, U>(component: Type<AbstractDialogComponent<T, U>>,
options?: ModalDialogOptions & { context: T }): Observable<U> {
options = { context: {}, viewContainerRef: this.vcRef,
fullscreen: true , ...options || {} };
return Observable.fromPromise(this.modal.showModal(component, options));
}
The error is: Type '{}' is not assignable to type T
on the second line. 错误是:
Type '{}' is not assignable to type T
第二行的Type '{}' is not assignable to type T
What am I missing here? 我在这里想念什么?
T
can be any type that extends {[key: string]: any}
, so it could for example be { requiredField: number }
. T
可以是任何扩展{[key: string]: any}
,因此它可以是{ requiredField: number }
。 If T
is this type, the value {}
is not a valid default for the T
since T
has required fields. 如果
T
是这种类型,则值{}
不是T
的有效默认值,因为T
具有必填字段。 Thus the compiler disallows the assignment of {}
since there are calls where it would not be valid. 因此,编译器不允许分配
{}
因为在存在无效调用的情况下会有调用。
The usual way to get around this is to use a type assertion : 解决此问题的通常方法是使用类型断言:
(...options || ({} as T))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.